Languages
[Edit]
EN

Java - get milliseconds from date time in string

8 points
Created by:
AnnLen
1777

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.