0

I'm trying to get the current day's date at 6 am in the format yyyy-MM-dd HH:mm:ss, but it shows as : Wed Dec 20 06:00:00 CST 2017

This is my code:

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
    Date date0 = new Date();
    String x = dateFormat.format(date0);         

    try{
        DateFormat formatter ; 
        Date date ; 
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = formatter.parse(x);

    }
    catch (Exception e){}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
MSV123
  • 39
  • 8
  • 2
    `Date` doesn't have an internal concept of "format", when you use `Date#toString`, it tends to use the current Locale's format, so, you'd need to reformat the result. In this case, you'd be WAY better off using the new Date/Time API, it would be simpler to set the time through – MadProgrammer Dec 20 '17 at 22:00
  • 1
    Add e.printStackTrace(); in catch and tell us the error – Squareoot Dec 20 '17 at 22:01
  • 2
    @StringForever as I understand OP's question, it isn't throwing any exception. The formatting itself works fine but OP desires a different format than the resulting one. It is just bad practice unrelated to the actual question. – Sync Dec 20 '17 at 22:03
  • Add Locale.getDefault() to get the locale time:- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String time = dateFormat .format(new Date()); – D_Alpha Dec 20 '17 at 22:11
  • Is there any reason why you are using the long outdated `Date` class and the notoriously troublesome `SimpleDateFormat`? Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 20 '17 at 22:50
  • @OleV.V. Yea, i'm very very new at java development, I'm doing modifications to a software that was already coded, I don't know much about old or new libraries and that stuff :/, thanks for the tip – MSV123 Dec 20 '17 at 22:53

3 Answers3

3

java.util.Date is a container for the number of milliseconds since the Unix Epoch, it doesn't not maintain any kind of internal formatting concept, instead, when you print it, it use Date#toString which generally uses the current Locale to provide a human readable representation of the value.

While I'm sure you could continue to mess about with Date to make this work, a much simpler approach would be to take advantage of the newer Date/Time API, something like...

LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.withHour(6).withMinute(0).withSecond(0).withNano(0);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(then);
System.out.println(formatted);

Which, for me, prints out 2017-12-21 06:00:00

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    Good answer. A possible alternative to explicitly setting minutes, seconds and nanos to 0 is `.truncatedto(ChronoUnit.HOURS)`. Mostly a matter of taste. – Ole V.V. Dec 21 '17 at 05:45
2

TL;DR

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    LocalDate date0 = LocalDate.now(ZoneId.of("America/Winnipeg"));
    String at6Am = date0.atTime(LocalTime.of(6, 0)).format(formatter);
    System.out.println(at6Am);

Running just now this printed

2017-12-21 06:00:00

Details

The classes that you use, Date and SimpleDateFormat, have been around since Java 1.0, some 20 years. They have proved to be poorly designed and cumbersome to use. Maybe for that reason too, much has been written about them, and from searching the web you could easily get the impression that these are the classes you should use. On the contrary, they are the classes you should avoid. Their replacement came out with Java 8, it will soon be 4 years ago.

Formatters are for formatting and parsing. You shouldn’t use a formatter, even less two formatters, for changing the time-of-day to 6 AM.

It is never the same date everywhere on the globe. So getting today’s date is an operation that depends on a time zone. I have made the time zone explicit in my code so the reader will also be aware of this fact. Please substitute your desired time zone if it didn’t happen to be America/Winnipeg.

You are modifying existing software. If you got an old-fashioned Date object from it, first convert it to the modern Instant type, then use the modern API for further operations. For example:

    Date date0 = getOldfashionedDateFromLegacyApi();
    String at6Am = date0.toInstant()
            .atZone(ZoneId.of("America/Winnipeg"))
            .with(LocalTime.of(6, 0))
            .format(formatter);

What went wrong in your code?

I don’t think there’s anything really wrong with the code in your question. You wanted your date-time formatted as 2017-12-20 06:00:00, and you got that in the string x in the third code line. Be happy with that and leave out the remainder of the code.

There is no such thing as imposing the format on the date-time objects, (no matter if we talk the outdated or the modern API). Formatting a date-time means converting it to a String in the desired format.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

After parsing, you need to format it as follows: formatter.format(date). So modify your code as follows:

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
    Date date0 = new Date();
    String x = dateFormat.format(date0);         

    try{
              DateFormat formatter ; 
              Date date ; 
              formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              date = formatter.format(formatter.parse(x));

   }
   catch (Exception e){}
JMA
  • 1,781
  • 9
  • 18