60

I need to create two date objects. If the current date and time is March 9th 2012 11:30 AM then

  • date object d1 should be 9th March 2012 12:00 AM
  • date object d2 should contain the current date itself

The date will not be entered, it is system date.

Update:

Date dt = new Date();
System.out.print(dt.toString());

gives current date and time

Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
Akhil K Nambiar
  • 3,835
  • 13
  • 47
  • 85

12 Answers12

61
    Calendar c = new GregorianCalendar();
    c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    Date d1 = c.getTime(); //the midnight, that's the first second of the day.

should be Fri Mar 09 00:00:00 IST 2012

Nishant
  • 54,584
  • 13
  • 112
  • 127
31
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println(sdf.format(date));
azizbekian
  • 60,783
  • 13
  • 169
  • 249
yen1k
  • 558
  • 3
  • 9
25

Here is a Java 8 based solution, using the new java.time package (Tutorial).

If you can use Java 8 objects in your code, use LocalDateTime:

LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();


If you require legacy dates, i.e. java.util.Date:

Convert the LocalDateTime you created above to Date using these conversions:

LocalDateTime -> ZonedDateTime -> Instant -> Date

  1. Call atZone(zone) with a specified time-zone (or ZoneId.systemDefault() for the system default time-zone) to create a ZonedDateTime object, adjusted for DST as needed.

    ZonedDateTime zdt = midnight.atZone(ZoneId.of("America/Montreal"));
    
  2. Call toInstant() to convert the ZonedDateTime to an Instant:

    Instant i = zdt.toInstant()
    
  3. Finally, call Date.from(instant) to convert the Instant to a Date:

    Date d1 = Date.from(i)
    


In summary it will look similar to this for you:

LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
Date d1 = Date.from(midnight.atZone(ZoneId.systemDefault()).toInstant());
Date d2 = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());


See also section Legacy Date-Time Code (The Java™ Tutorials) for interoperability of the new java.time functionality with legacy java.util classes.

Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
10
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=>  " + dateNow);
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
4

If you are able to add external libs to your project. I would recommend that you try out Joda-time. It has a very clever way of working with dates.

http://joda-time.sourceforge.net/

heldt
  • 4,166
  • 7
  • 39
  • 67
  • +1 for suggesting Joda. its DateMidnight class should do it for you. – Ashwini Raman Mar 09 '12 at 06:45
  • 3
    @AshwiniRaman No, not `DateMidnight` any longer. All the "midnight"-related classes and methods in Joda-Time have been deprecated. They were based on faulty ideas. Instead use the [`withTimeAtStartOfDay`](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay--) method on `DateTime`. – Basil Bourque Jul 30 '15 at 07:42
3

Using org.apache.commons.lang3.time.DateUtils

Date pDate = new Date();
DateUtils.truncate(pDate, Calendar.DAY_OF_MONTH);
TheBakker
  • 2,852
  • 2
  • 28
  • 49
3

A solution in Java 8:

Date startOfToday = Date.from(ZonedDateTime.now().with(LocalTime.MIN).toInstant());
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
  • 3
    Using Java 8 is great. Two suggestions: (1) Give explicit time zone. (2) Use `LocalDate.now(ZoneId.of("Asia/Karachi")).atStartOfDay(ZoneId.of("Asia/Karachi"))` to take the case into account where the day doesn’t begin at 00:00 (typically at transition to summer time (DST)). Alternatively use `ZonedDateTime.truncatedTo()`. – Ole V.V. Jan 20 '18 at 11:59
2

Here is a Java 8 way to get UTC Midnight in millis

ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
long todayMidnight = utcTime.toLocalDate().atStartOfDay().toEpochSecond(ZoneOffset.UTC) * 1000;
1

For Current Date and Time :

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

This will shown as :

Feb 5, 2013 12:40:24PM

Manish Dubey
  • 4,206
  • 8
  • 36
  • 65
1
private static Date truncateTime(Calendar cal) {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return new Date(cal.getTime().getTime());
}
 public static void main(String[] args) throws Exception{
        Date d2 = new Date();
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(d2);
        Date d1 = truncateTime( cal );
        System.out.println(d1.toString());
        System.out.println(d2.toString());
}
Jaydeep Rajput
  • 3,605
  • 17
  • 35
0

Defining ‘Midnight’

The word “midnight” is tricky to define.

Some think of it as the moment before a new day starts. Trying to represent that in software as tricky as the last moment of the day can always be subdivided as a smaller fraction of a second.

I suggest a better way of thinking about this is to get “first moment of the day”.

This supports the commonly used approach of defining a span of time as ‘Half-Open’, where the beginning is inclusive while the ending is exclusive. So a full day starts with the first moment of the day and runs up to, but not including, the first moment of the following day. A full day would like this (notice the date going from the 3rd to the 4th):

2016-02-03T00:00:00.0-08:00[America/Los_Angeles]/2016-02-04T00:00:00.0-08:00[America/Los_Angeles]

Joda-Time

If using the Joda-Time library, call withTimeAtStartOfDay.

Note how we specify the time zone. If omitted, the JVM’s current default time zone is implicitly applied. Better to be explicit.

DateTime todayStart = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay() ;

If using Java 8 or later, better to use the java.time package built into Java. See sibling Answer by Jens Hoffman.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
Date date = new Date(); System.out.println(dateFormat.format(date));    //2014/08/06 15:59:4