Showing posts with label LocalDate. Show all posts
Showing posts with label LocalDate. Show all posts

Monday, 20 April 2020

Java Convert LocalDate to Date

'java.util.Date' represent date + time + timezone whereas 'java.time.LocalDate' represent only date portion.

Below snippet converts the Date to LocalDate.

Date date = new Date();
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = instant.atZone(zoneId);
LocalDate localDate = zonedDateTime.toLocalDate();

App.java
package com.sample.app;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class App {

	public static void main(String args[]) throws InterruptedException {

		Date date = new Date();
		Instant instant = date.toInstant();
		ZoneId zoneId = ZoneId.systemDefault();
		ZonedDateTime zonedDateTime = instant.atZone(zoneId);
		LocalDate localDate = zonedDateTime.toLocalDate();

		System.out.println("localDate : " + localDate);

	}

}

Output
localDate : 2020-03-07



You may like
Previous                                                    Next                                                    Home

Monday, 13 April 2020

Get LocalDate from long epoch time

'ZonedDateTime' class provides 'toLocalDate' method to convert ZonedDateTime to LocalDate.

Following snippet is used to get LocalDate from epoch.
LocalDate localDate = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();

App.java
package com.sample.app;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

public class App {

 public static LocalDate getLocalDate(long epoch) {
  LocalDate localDate = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();
  return localDate;
 }

 public static void main(String args[]) throws ClassNotFoundException {
  LocalDate localDate = getLocalDate(1234567890l);
  
  System.out.println(localDate);
 }
}

Output
1970-01-15

You may like
Previous                                                    Next                                                    Home