Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get Time in Milliseconds for the Given date and time in Java?
The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string.
- One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object.
- To parse/convert a string as a Date object Instantiate this class by passing desired format string.
- Parse the date string using the parse() method.
- You can get the epoch time using the getTime() method.
Example
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sample {
public static void main(String args[]) throws ParseException {
//Instantiating the SimpleDateFormat class
SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//Parsing the given String to Date object
String str = "25-08-2009 11:20:45";
Date date = dateformatter.parse(str);
long msec = date.getTime();
System.out.println("Epoch of the given date: "+msec);
}
}
Output
Epoch of the given date: 1251179445000
You can set date and time values to a calendar object using the set() method. The getTimeInMillis() of this class returns the epoch time of the date value.
Example
import java.util.Calendar;
public class Sample {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
cal.set(2014, 9, 11, 10, 25, 30);
long msec = cal.getTimeInMillis();
System.out.print(msec);
}
}
Output
1413003330758
You can set date and time values to a ZonedDateTime object using the of() method. The toEpochMilli() of the Instant class returns the epoch time of the date value.
Example
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Sample {
public static void main(String args[]){
//Creating the ZonedDateTime object
ZoneId id = ZoneId.of("Asia/Kolkata");
ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id);
Instant instant = obj.toInstant();
long msec = instant.toEpochMilli();
System.out.println("Milli Seconds: "+msec);
}
}
Output
Milli Seconds: 1410411330000
Advertisements