Last active
July 12, 2018 20:05
-
-
Save iamitshri/735e25a8ad74114027f56ba4f2051c88 to your computer and use it in GitHub Desktop.
Java: Convert a give util date to a util date at the start of the day
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package katas; | |
import java.time.Instant; | |
import java.time.LocalDateTime; | |
import java.time.OffsetDateTime; | |
import java.time.ZoneId; | |
import java.util.Calendar; | |
import java.util.Date; | |
public class Main { | |
public static void main(String[] args) { | |
Calendar cal = Calendar.getInstance(); | |
cal.setTime(Date.from(Instant.now())); | |
// Current Time | |
System.out.println("current Time: "+cal.getTime()); | |
cal.set(Calendar.HOUR_OF_DAY, 0); | |
cal.set(Calendar.MINUTE, 0); | |
cal.set(Calendar.SECOND, 0); | |
cal.set(Calendar.MILLISECOND, 0); | |
// Start of the day - 1 | |
System.out.println("With Calendar: "+cal.getTime()); | |
// Start of the day using Java 8 | |
Date input = new Date(); | |
LocalDateTime d = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().atStartOfDay(); | |
Date newdateatstart = Date.from(d.toInstant(OffsetDateTime.now(ZoneId.systemDefault()).getOffset())); | |
System.out.println("With Java8 Api:"+newdateatstart); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment