Im trying to set the Calendar
date object in the following way, but I don't know how.
public void setTradeDate(String tradeDate) {
Calendar tradeDate = ?
}
The String
is in the format:
String tradeDate = "2017-06-01T15:49:18Z";
Answer
To create a Calendar
from a String
, you can use a SimpleDateFormat
(as already suggested by the other answers). The formatter will parse the String
and create a Date
object, which will be set to the Calendar
:
String tradeDate = "2017-06-01T15:49:18Z";
// create Calendar
Calendar cal = Calendar.getInstance();
// create formatter
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
// parse string and set the resulting date to Calendar
cal.setTime(df.parse(tradeDate));
The Calendar
will contain the date equivalent to 2017-06-01T15:49:18Z
. Note that this date/time is in UTC - the Z
in the end is the UTC designator.
But if you try to print this date (using System.out.println(cal.getTime())
, a logger, or even checking its value in a debugger), it'll implicity use the toString()
method, and this converts the fields (day, month, year, hour, minute, seconds, etc) to the system's default timezone (if your default timezone is in India, for example, the date will be printed as Thu Jun 01 21:19:18 IST 2017
, although the internal value won't be changed). But the value will still be equivalent to the UTC input.
Don't be misleaded by the output of toString()
method from Calendar
and Date
classes. What matters is the value of the timestamp: the number of milliseconds since 1970-01-01T00:00Z
, which can be checked with cal.getTimeInMillis()
. Check this article for more information.
As you're using Java 7, there's another (better) alternative: you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes.
You can parse the input to a org.threeten.bp.ZonedDateTime
and use the org.threeten.bp.DateTimeUtils
class to convert it to a java.util.Calendar
:
String tradeDate = "2017-06-01T15:49:18Z";
// parse input
ZonedDateTime zdt = ZonedDateTime.parse(tradeDate);
// convert to calendar
Calendar cal = DateTimeUtils.toGregorianCalendar(zdt);
Using this backport eliminates lots of problems and design issues of the old Calendar
API. And makes a future migration to Java 8 much easier, as in new Java 8 API the classes and methods names are the same, just the packages are different (in Java 8 is java.time
and in ThreeTen Backport is org.threeten.bp
).
No comments:
Post a Comment