Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, December 21, 2020

Java.lang.System.currentTimeMillis() Method Example

1. Overview

In this tutorial, We'll learn how to get the current time value in milliseconds in java

Java api provides a utility class System in java.lang package and System class has static method which can be directly invoked as System.currentTimeMillis().

Java.lang.System.currentTimeMillis() Method Example


2. Syntax

public static long currentTimeMillis()


From syntax, we can see that it returns a long value in milli seconds time unit.

The returned value is dependent on the underlying operating system. For example, some of the operating systems generates the time in tens of milliseconds.

This method returns the value that is difference between the current system time and coordinated UTC time 1970.


3. System.currentTimeMillis() Examples


The below example is on how to use System.currentTimeMillis() method.

package com.javaprogramto.java8.dates;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import org.joda.time.DateTime;

/**
 * Example to get the current time in milli seconds.
 * 
 * @author JavaProgramTo.com
 *
 */
public class CurrentTimeSystemCurrentTimeMillis {

	public static void main(String[] args) {

		// calling currentTimeMillis() method
		long currentTimeMillis = System.currentTimeMillis();
		System.out.println("Current time in millies - "+currentTimeMillis);
		
		// using Date(long) constructor
		Date date = new Date(currentTimeMillis);
		System.out.println("Date : "+date);
		
		// java 8
		LocalDateTime localDateTime = Instant.ofEpochMilli(currentTimeMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
		System.out.println("Java 8 localdate time : "+localDateTime);
	}
}

Output:

Current time in millies - 1608565975991
Date : 2020-12-21
Java 8 localdate time : 2020-12-21T21:22:55.991


In the above program, First we have retrieved the current date and time in milli seconds as long value and next converted the long value into Date value.

And also converted the long value into LocalDateTime object in java 8.


4. Conclusion

In this article, We've seen how to get the current date time in milli seconds in java.

GitHub

Java 8 Date Time Examples

No comments:

Post a Comment

Please do not add any spam links in the comments section.