简体   繁体   中英

How to convert String do Java.util.Date including ISO8601

I'm getting the following String from a connector:

"2014-04-11T13:25:58.025+02:00"

I've also the actual time:

Calendar cal = Calendar.getInstance();
long timeNow = cal.getTimeInMillis();

I should define, if the date from the connector is older than 10 minutes. So I've tried to compare this two dates with milliseconds.

//example date
String timeString = "2014-04-11T13:25:58.025+02:00";
long difference = 660000;

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
cSchedStartCal = DatatypeConverter.parseDateTime(timeString);
Date date = new Date(cSchedStartCal.getTime().getTime());

if (date.getTime() + difference < timeNow) {
  System.out.println("too old");
} else {
  System.out.println("ok");
}

But when the date is not to old, I've get it's too old because there must be a problem with the timezones.

The attribute date is always without +02:00 and that is the problem. Is it possible to add the timezone hours to the date in a propper way?

And I don't have the possibility to use the joda library.

You need:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
java.util.Date d = sdf.parse("2014-04-11T13:25:58.025+02:00");

XXX works with Java 7 and later.

For your second question, why not this simple approach leaving your timezone and Calendar -code out? Many people associate temporal amounts like 10 minutes with reference to global time, not if you might be during a DST-jump in local timezone.

if (d.getTime() + 10 * 60 * 1000L < System.currentTimeMillis()) {
  System.out.println("too old");
} else {
  System.out.println("ok");
}

UPDATE due to comment:

d.getTime() yields the unix epoch time in milliseconds corresponding to 2014-04-11T13:25:58.025+02:00

This epoch value does not change if you choose following similar representation with SAME instant:

2014-04-11T13:25:58.025+02:00
2014-04-11T12:25:58.025+01:00
2014-04-11T11:25:58.025Z (zero offset - zulu time)

The representation 2014-04-11T15:25:58.025 has no offset and is therefore not comparable. Remember that such representations consist of local time plus offset. So in order to get global time in UTC timezone you have to SUBTRACT offset, not to add offset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM