Get Today's date in Java at midnight time

前端 未结 12 1957
北海茫月
北海茫月 2020-12-09 07:08

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 20
相关标签:
12条回答
  • 2020-12-09 08:06
    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);
    
    0 讨论(0)
  • 2020-12-09 08:06

    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

    0 讨论(0)
  • 2020-12-09 08:06

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

    Date pDate = new Date();
    DateUtils.truncate(pDate, Calendar.DAY_OF_MONTH);
    
    0 讨论(0)
  • 2020-12-09 08:08

    A solution in Java 8:

    Date startOfToday = Date.from(ZonedDateTime.now().with(LocalTime.MIN).toInstant());
    
    0 讨论(0)
  • 2020-12-09 08:09

    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;
    
    0 讨论(0)
  • 2020-12-09 08:10

    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.

    0 讨论(0)
提交回复
热议问题