Get the current date with the time 00:00:00 in Java

1

I have the following code:

Calendar.getInstance().getTime();

With that I get the current date, but I want to know if there is any way that the time is 00:00:00 instead of when that method was called.

    
asked by Gonzalo Sámano 07.12.2016 в 17:33
source

4 answers

3

You must enter the time you want by hand. In your case it would be:

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

And at the end you have what you want with the same to have the Date :

c.getTime();

The output it gives you would be:

  

Wed Dec 07 00:00:00 CET 2016

    
answered by 07.12.2016 / 19:36
source
2

Using Java 8 ( java.time ):

❑ Code :

ZoneId zona = ZoneId.systemDefault();
LocalDate ahora = LocalDate.now();
ZonedDateTime inicioHoy = ahora.atStartOfDay(zona);
Instant instante = inicioHoy.toInstant();
Date fecha = Date.from(instante);

System.out.println(zona);
System.out.println(ahora);
System.out.println(inicioHoy);
System.out.println(instante);
System.out.println(fecha);
// En una línea
Date fecha = Date.from(LocalDate.now().atStartOfDay(zona).toInstant());

❑ Exit :

America/Mexico_City
2016-12-07
2016-12-07T00:00-06:00[America/Mexico_City]
2016-12-07T06:00:00Z
Wed Dec 07 00:00:00 CST 2016

To learn more, see Java SE 8 Date and Time .

    
answered by 07.12.2016 в 20:02
2

Hi With JAVA 8, you can do it like this:

LocalDateTime fechaHora LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0))
//teniendo el resultado : 2017-02-07T00:00
    
answered by 08.02.2017 в 01:24
1

Calendar.HOUR uses 0-11 (for use with AM / PM).

Field number for Get and Set indicating the time of morning or afternoon.

TIME is used for the 12-hour clock (0 - 11).

Noon and midnight are represented by 0, not by 12.

Example:

package mx.com.softmolina;

import java.text.SimpleDateFormat;

import java.util.Calendar;

/**
 *
 * @author SoftMolina
 */

public class SetTime {

    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR, 17);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 2);
        System.out.println(simpleDateFormat.format(calendar.getTime()));

    }

}

Result: 08-12-2016 05:30:02

In the previous example, as you can see, we are indicating that it shows us the 5 o'clock hour with 30 minutes and 2 seconds.

link

    
answered by 07.12.2016 в 20:58