0

I want to get Today's date in epoch or milisecs, but with the time part set to start of today i.e. 24:00(midnight)

For example

At the moment time is 10-APR-2013 17:56:44.455 which in

mili-seconds is 1365613004461
epoch = 1365613004

Can some one please tell me how to get epoch for 10-APR-2013 24:00:00?

kaderud
  • 5,378
  • 2
  • 35
  • 49
Khurram Majeed
  • 2,231
  • 7
  • 37
  • 57

2 Answers2

3

You could set the time to 0:00:00 like this:

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("dd-MM-yy HH:mm:ss.S").format(cal.getTime()));

cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

System.out.println(new SimpleDateFormat("dd-MM-yy HH:mm:ss.S").format(cal.getTime()));

The first value prints as 10-04-13 18:10:40.832 and the second 10-04-13 00:00:00.0.

assylias
  • 310,138
  • 72
  • 642
  • 762
  • You'll want to set the `Calendar`'s (and `SimpleDateFormat`'s) `TimeZone` to `"UTC"` before doing these manipulations, or your result will be incorrect. – jpm Apr 10 '13 at 19:38
1

java.time

The JSR-310 implementation, also known as java.time or the modern date-time API provides us with two ways to get it:

  1. LocalDate#atStartOfDay: Combines a date with the time of midnight to create a LocalDateTime at the start of this date.
  2. LocalDate#atStartOfDay(ZoneId zone): Returns a ZonedDateTime from this date at the earliest valid time according to the rules in the time-zone.

Demo:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        LocalDateTime ldt1 = LocalDate.of(2016, Month.MARCH, 27).atStartOfDay();
        LocalDateTime ldt2 = LocalDate.of(2016, Month.MARCH, 28).atStartOfDay();
        ZonedDateTime zdt1 = LocalDate.of(2016, Month.MARCH, 27).atStartOfDay(ZoneId.of("Europe/London"));
        ZonedDateTime zdt2 = LocalDate.of(2016, Month.MARCH, 28).atStartOfDay(ZoneId.of("Europe/London"));
        System.out.println(ldt1);
        System.out.println(ldt2);
        System.out.println(zdt1);
        System.out.println(zdt2);
    }
}

Output:

2016-03-27T00:00
2016-03-28T00:00
2016-03-27T00:00Z[Europe/London]
2016-03-28T00:00+01:00[Europe/London]

enter image description here Source: timeanddate.com

Learn more about java.time, the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 62,771
  • 5
  • 54
  • 92