简体   繁体   中英

How to convert date to milliseconds with out timezone offset?

I what to convert selected date to milliseconds without timezone difference. Below is my code.

 String selectedDate=Jan 18, 2020;
 SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
 Date date = format.parse(selectedDate);

while running I am getting date like Sat Jan 18 00:00:00 GMT+05:30 2020. But I want without timezone difference like Jan 18, 2020.

For a difference of 0 from UTC:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMM dd, uuuu", Locale.ENGLISH);
    String selectedDate = "Jan 18, 2020";
    ZonedDateTime zdt = LocalDate.parse(selectedDate, dateFormatter)
            .atStartOfDay(ZoneOffset.UTC);
    System.out.println(zdt);
    long millisSinceEpoch = zdt.toInstant().toEpochMilli();
    System.out.println(millisSinceEpoch);

Output from this snpipet is:

 2020-01-18T00:00Z 1579305600000

I am using java.time, the modern Java date and time API. The classes that you used, SimpleDateFormat and Date , are poorly designed and long outdated, and no one should use them anymore.

Question: Doesn't java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

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