Languages
[Edit]
EN

Java - get milliseconds from date time in string

8 points
Created by:
AnnLen
9180

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join