Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

Java - get milliseconds from date time in string

0 contributions
8 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more