How to Get Unix Timestamp in Milliseconds in Java


In this example we will show two methods to get Unix Timestamp in milliseconds in Java:

Date class – getTime() method
Calendar class – getTimeInMillis() method

Source Code

Method 1:

package com.beginner.examples;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetMillisecondsTimeExample1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		String strDate = "2019-02-02 10:25:30";
		try {
			Date date = dateFormat.parse(strDate);

			System.out.println("This date:" + strDate);
			System.out
					.println("The number of milliseconds from 1970-01-01 to this date: "
							+ date.getTime());
		} catch (ParseException e) {
			// TODO: handle exception
			System.out.println(e.toString());
		}

		System.out.println();
	}
}

Output:

This date:2019-02-02 10:25:30
The number of milliseconds from 1970-01-01 to this date: 1549074330000

Method 2:

package com.beginner.examples;

import java.util.Calendar;
import java.util.Date;

public class GetMillisecondsTimeExample2 {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		System.out
				.println("The number of milliseconds from 1970-01-01 to this time: "
						+ c.getTimeInMillis());
	}
}

Output:

The number of milliseconds from 1970-01-01 to this time: 1554041755377

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments