Languages
[Edit]
EN

Java - get milliseconds from date time in string

8 points
Created by:
Broncono
466

In java we can get milliseconds with following methods:

  • Date class - getTime() method
  • Instant class - toEpochMilli() method
  • Calendar class - getTimeInMillis() method

1. Get milliseconds with Date

String dateTimeStr = "2019-08-10 02:39:00:123";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
Date date = sdf.parse(dateTimeStr);

System.out.println(date.getTime());

Output:

1565397540123

2. Get milliseconds with Instant (Java 8)

String dateTimeStr = "2019-08-10 02:39:00:123";
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeStr,
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));

Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

System.out.println(instant.toEpochMilli()); // 1565397540123

Output:

1565397540123

3. Get milliseconds with Calendar

String dateTimeStr = "2019-08-10 02:39:00:123";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
Date date = sdf.parse(dateTimeStr);

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

System.out.println(calendar.getTimeInMillis()); // 1565397540123

Output:

1565397540123

References

  1. Date - Java docs
  2. Instant - Java docs
  3. Calendar - Java docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join