Javaexercise.com

How To Get Seconds From LocalDateTime In Java?

To get the seconds from the local date-time, Java provides a class i.e. LocalDateTime, and a built-in method i.e. getSecond().

In this article, we are getting seconds from the local date-time instance.

Let's see the code below.

/* 
 *  Code example to get seconds from localdatetime in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// String  date is given
		String strDate = "2022-03-14T17:28:13.048999208";
		// parse the String date into date time
		LocalDateTime date = LocalDateTime.parse(strDate);

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get seconds from the date
		int seconds = date.getSecond();

		// Display result
		System.out.println("Seconds : "+seconds);
	}
}

Output:

Date : 2022-03-14T17:28:13.048999208
Seconds : 13
 

In the above code, we first parsed the String date to LocalDateTime object by using the parse() method. 

If you already have locadatetime object, then you don't need to parse it. 

You can directly call the getSecond() method.

Now,  let's have a look at this method signature:

public int getSecond()

Package Name: java.time

Class Name: LocalDateTime

Return Value: It returns the second-of-minute, from 0 to 59.

Parameters: It does not take any parameters.

Exceptions: It does not throw any exception.

Version: Since 1.8

 

Let's understand with one more example:

How to get seconds from the current date-time in Java

If you want to get seconds from the current local date-time then used the below code.

Here, we used the now() method to get the current date-time and then used the getSecond() method to get the seconds.

/* 
 *  Code example to get seconds from localdatetime in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// Current date and time
		LocalDateTime date = LocalDateTime.now();

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get seconds from the date
		int seconds = date.getSecond();

		// Display result
		System.out.println("Seconds : "+seconds);
	}
}

Output:

Date : 2022-03-16T12:18:46.106602758
Seconds : 46