Set the time to 00:00:00

I have a problem reloading the clock in Java. For a given date, I want to set the clock to 00:00:00.

This is my code:

/** * Resets milliseconds, seconds, minutes and hours from the provided date * * @param date * @return */ public static Date trim(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR, 0); return calendar.getTime(); } 

The problem is that sometimes the time is 12:00:00 , and sometimes it is 00:00:00 , and when I query the database for the object that was saved on 07.02.2013 00:00:00 , and the actual time of the object, which stored, equal to 12:00:00 request ends with an error.

I know that 12:00:00 == 00:00:00 !

I am using AppEngine. Is this appengine bug, problem or some other problem? Or does it depend on something else?

+103
java java.util.calendar
Jul 23 '13 at 21:44
source share
12 answers

Use a different constant instead of Calendar.HOUR , use Calendar.HOUR_OF_DAY .

 calendar.set(Calendar.HOUR_OF_DAY, 0); 

Calendar.HOUR uses 0-11 (for use with AM / PM), and Calendar.HOUR_OF_DAY uses 0-23.

To quote Javadocs:

public static final int HOUR

The number of the field to receive and set, indicating the hour of the morning or afternoon. HOUR is used for a 12-hour clock (0 - 11). Noon and midnight are represented by 0, not 12. For example, during 10: 04: 15 h. 50 m. HOUR is 10.

and

public static final int HOUR_OF_DAY

Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for a 24-hour clock. For example, during 10: 04: 15,250 PM, HOUR_OF_DAY is 22.

Testing ("now" at present p. 14:55 July 23, 2013 Pacific Daylight Time):

 public class Main { static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); System.out.println(sdf.format(now.getTime())); now.set(Calendar.HOUR_OF_DAY, 0); System.out.println(sdf.format(now.getTime())); } } 

Output:

 $ javac Main.java $ java Main 2013-07-23 12:00:00 2013-07-23 00:00:00 
+173
Jul 23 '13 at 21:45
source share

java.time

Using the java.time framework built into Java 8 and later. See Tutorial .

 import java.time.LocalTime; import java.time.LocalDateTime; LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224 # start of a day now.with(LocalTime.MIN); # 2015-11-19T00:00 now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00 

If you do not need the time of day (hour, minute, second, etc.), consider using LocalDate .

 LocalDate.now(); # 2015-11-19 
+18
Nov 19 '15 at 18:54
source share

Here are some useful features that I use for this.

 /** * sets all the time related fields to ZERO! * * @param date * * @return Date with hours, minutes, seconds and ms set to ZERO! */ public static Date zeroTime( final Date date ) { return DateTimeUtil.setTime( date, 0, 0, 0, 0 ); } /** * Set the time of the given Date * * @param date * @param hourOfDay * @param minute * @param second * @param ms * * @return new instance of java.util.Date with the time set */ public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms ) { final GregorianCalendar gc = new GregorianCalendar(); gc.setTime( date ); gc.set( Calendar.HOUR_OF_DAY, hourOfDay ); gc.set( Calendar.MINUTE, minute ); gc.set( Calendar.SECOND, second ); gc.set( Calendar.MILLISECOND, ms ); return gc.getTime(); } 
+11
Jul 23 '13 at 21:50
source share

It is best to set the time zone for the DateFormat component as follows:

 DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

Then you can get the time β€œ00:00:00” by passing 0 milliseconds to the formatter:

 String time = dateFormat.format(0); 

or you can create a Date object:

 Date date = new Date(0); // also pass milliseconds String time = dateFormat.foramt(date); 

or you will have more options using the Calendar component, but you should also set the time zone as GMT for the calendar instance:

 Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US); calendar.set(Calendar.HOUR_OF_DAY, 5); calendar.set(Calendar.MINUTE, 37); calendar.set(Calendar.SECOND, 27); dateFormat.format(calendar.getTime()); 
+3
Oct 27 '17 at 15:51 on
source share

Another JAVA 8 way:

 LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS); 

But it’s much more convenient to edit a date that already exists.

+2
Jul 26 '17 at 11:47
source share

Doing this might be easier (in Java 8)

 LocalTime.ofNanoOfDay(0) 
+1
Feb 28 '17 at 13:40
source share

We can set the java.util.Date time to 00:00:00 using the LocalDate Java 8 / Joda-datetime api class:

 Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018 LocalDate localDate = LocalDate.fromDateFields(datewithTime); Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018 
+1
Jul 20 '18 at 10:31
source share

Another way to do this is to use DateFormat without any seconds:

 public static Date trim(Date date) { DateFormat format = new SimpleDateFormat("dd.MM.yyyy"); Date trimmed = null; try { trimmed = format.parse(format.format(date)); } catch (ParseException e) {} // will never happen return trimmed; } 
0
Aug 20 '15 at 9:46
source share

You can do this with the following:

 Calendar cal = Calendar.getInstance(); cal.set(year, month, dayOfMonth, 0, 0, 0); Date date = cal.getTime(); 
0
Mar 31 '18 at 0:20
source share

If you need the 00:00:00 format per line, you should use SimpleDateFormat as shown below. Using "H" instead of "H".

 Date today = new Date(); SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); //not SimpleDateFormat("dd-MM-yyyy hh:mm:ss") Calendar calendarDM = Calendar.getInstance(); calendarDM.setTime(today); calendarDM.set(Calendar.HOUR, 0); calendarDM.set(Calendar.MINUTE, 0); calendarDM.set(Calendar.SECOND, 0); System.out.println("Current Date: " + ft.format(calendarDM.getTime())); //Result is: Current Date: 29-10-2018 00:00:00 
0
Oct 29 '18 at 3:46
source share

Since Java8 adds new Date features, we can do this easily.

 // If you have instant, then: Instant instant1 = Instant.now(); Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS); System.out.println(day1); //2019-01-14T00:00:00Z // If you have Date, then: Date date = new Date(); Instant instant2 = date.toInstant(); Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS); System.out.println(day2); //2019-01-14T00:00:00Z // If you have LocalDateTime, then: LocalDateTime dateTime = LocalDateTime.now(); LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS); System.out.println(day3); //2019-01-14T00:00 String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); System.out.println(format);//2019-01-14T00:00:00 
0
Jan 14 '19 at 5:50
source share

TL; dr

 myJavaUtilDate // The terrible 'java.util.Date' class is now legacy. Use *java.time* instead. .toInstant() // Convert this moment in UTC from the legacy class 'Date' to the modern class 'Instant'. .atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone). .toLocalDate() // Extract the date-only portion. .atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00. 

java.time

You are using the horrible old date and time classes that were superseded several years ago by the modern java.time classes defined in JSR 310.

Date βž™ Instant

java.util.Date represents the moment in UTC. Its replacement is Instant . Call the new conversion methods added to the old classes.

 Instant instant = myJavaUtilDate.toInstant() ; 

Timezone

Indicate the time zone in which you want your new time of day to make sense.

Enter the correct time zone name in Continent/Region format, for example, America/Montreal , Africa/Casablanca or Pacific/Auckland . Never use a 2-4 letter abbreviation, such as EST or IST as they are not true time zones, not standardized, and not even unique (!).

 ZoneId z = ZoneId.of( "America/Montreal" ) ; 

ZonedDateTime

Apply ZoneId to Instant to get ZonedDateTime . The same moment, the same point on the timeline, but a different wall clock time.

 ZonedDateTime zdt = instant.atZone( z ) ; 

Change the time of day

You asked to change the time of day. Apply LocalTime to change all parts of the time of day: hours, minutes, seconds, fractions of a second. A new ZonedDateTime with the values ​​based on the original. The java.time classes use this immutable object pattern to ensure thread safety .

 LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM. ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ; 

First moment of the day

But you asked specifically for 00:00. So, apparently, you want the first moment of the day. Caution: some days in some areas do not start at 00:00:00. They may start at other times, such as 01:00:00, due to anomalies such as daylight saving time (DST).

Let java.time determine the first moment. Retrieve part for date only. Then go through the time zone to get the first moment.

 LocalDate ld = zdt.toLocalDate() ; ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ; 

Set to UTC

If you need to return to UTC, retrieve Instant .

 Instant instant = zdtFirstMomentOfDay.toInstant() ; 

Instant βž™ Date

If you need java.util.Date to interact with old code that has not yet been updated to java.time, convert.

 java.util.Date d = java.util.Date.from( instant ) ; 
0
May 26 '19 at 20:22
source share



All Articles