java get time code example
Example 1: java how to get current date
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class CurrentDateTimeExample1 {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
}
}
Example 2: java get excectuon time
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
Example 3: How to get current date and time in java
// get current date and timein java using Calendar.getTime() method
import java.util.Calendar;
import java.util.Date;
public class UsingCalendarClass
{
public static void main(String[] args)
{
Date date = Calendar.getInstance().getTime();
System.out.println(date);
}
}
Example 4: How to get current date and time in java
// get current date and time in java using LocalDate.now() method
import java.time.LocalDate;
public class UsingLocalDate
{
public static void main(String[] args)
{
System.out.println(LocalDate.now());
}
}
Example 5: How to get current date and time in java
// get current date and time in java using LocalDateTime.now() method
import java.time.LocalDateTime;
public class UsingLocalDateTime
{
public static void main(String[] args)
{
System.out.println(LocalDateTime.now());
}
}
Example 6: java get current time in seconds
LocalDateTime date = LocalDateTime.now();
int seconds = date.toLocalTime().toSecondOfDay();