简体   繁体   中英

Convert ical time to milliseconds

I am trying to parse an iCal-file and write the info to a database for my Android application.

I am using the ical4j-library to parse the data, and as output I get, for example, a date formatted like this: 20140116T121500Z .

I want to convert that date into milliseconds. I tried using Joda, but couldn't get it to work:

Caused by: java.lang.IllegalArgumentException : Invalid format: "20140110T091500Z" is malformed at "1500Z"

Using Joda-Time API for DateTimeFormat :

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmssZ");
System.out.println(formatter.parseDateTime("20140116T121500Z").getMillis());

Output:

1389874500000

I am able to parse your date through java.text.SimpleDateFormat by escaping 'Z' representing the timezone (or omit Z altogether):

SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
System.out.println(dateFormat.parse("20140116T121500Z").getTime());

Output:

1389854700000

Note: The difference in the 2 times is introduced by diluting the timezone in java.text.SimpleDateFormat , which can be overcome by setting an explicit GMT timezone below:

SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.parse("20140116T121500Z").getTime());

Output:

1389874500000

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