简体   繁体   中英

Convert datetime to utc format

I have a datetime in string format with the specific time zone, but I cannot figure out to convert it into UTC format so as I could send it to the server backend and there it could be saved to the database.

String obtained after date and time picker: "30-9-2016 15:10 Asia/Kolkata" Need to convert it to UTC format

Try to use joda http://www.joda.org/joda-time/ .

This snippet results in "2016-09-30T09:40:00.000Z"

public String convert(String timeStamp) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("d-M-yyyy HH:mm ZZZ");
    DateTime dt = fmt.parseDateTime(timeStamp);
    return dt.toInstant().toString();
}

您可以使用 'currentDate.utc().format()' 将日期转换为 UTC。

The class SimpleDateFormat seems to lack an option to parse time zone identifiers like "Asia/Kolkata" (neither a zone name nor an offset). There is no pattern symbol VV representing exact this kind of tz information.

If you insist on using SimpleDateFormat you could circumvent this limitation by using string preprocessing like:

input = input.replace("Asia/Kolkata", "GMT+05:30");
// and then use pattern symbol "z" or "Z"

The main disadvantage is: You make hardwired assumptions about the concrete tz identifier used in your input.

However, there are at least three other libraries which are capable of parsing the identifier "Asia/Kolkata" or similar using the pattern symbol "VV".

a) ThreetenABP - an android adaptation of the backport of java.time-package in Java-8

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-M-yyyy HH:mm VV");
Instant instant = ZonedDateTime.parse(input, dtf).toInstant();
java.util.Date jud = new java.util.Date(instant.toEpochMilli());

b) Joda-Time-Android

see the answer of @sven4all

c) my library Time4A

ChronoFormatter<Moment> f =
  ChronoFormatter.ofMomentPattern(
    "d-M-yyyy HH:mm VV", PatternType.CLDR, Locale.ROOT, ZonalOffset.UTC);
Moment moment = f.parse(input);
java.util.Date jud = TemporalType.JAVA_UTIL_DATE.from(moment);

What so ever, for storing in a database, you will probably need different conversions for example to the type java.sql.Timestamp .

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