I got back a date from an API call in the following format: "2008-03-29T00:00:00Z". To parse this String and get a Date instance, I created a SimpleDateFormat instance as follows...
SimpleDateFormat myDateTimeFormat = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
... and then parsed my String representation of a Date as follows...
String myDateString = "2008-03-29T00:00:00Z";
Date myDate = myDateTimeFormat .parse(myDateString);
... To get back the original String value from the Date instance I would call the format(...) method as follows...
myDateString = myDateTimeFormat .format(myDateString);
... In a similar fashion, if I wanted to format a number as a String showing the pounds sterling currency symbol and two decimal places, I could do something like the following...
double myNumber = 25;
DecimalFormat myCurrencyFormat = new DecimalFormat("£#.00");
String myFormattedNumber = myCurrencyFormat.format(myNumber);
... The value of myFormattedNumber in the above example would be "£25.00".
Both dates and currencies can be formatted smarter using pre-defined formats and locale information. The above is intended only as a quick guide to get you started parsing and formatting dates and currencies.
No comments:
Post a Comment