3

I have a getter in Java 8 that I set to the below, problem is the output is Sat Jan 11 00:00:00 AEDT 2020

The class has to remain as a Date, StartDate is a LocalDate.

public static Date getStartDate() {
    return Date.from(StartDate.atStartOfDay()
                      .atZone(ZoneId.systemDefault())
                      .toInstant());
}

I need it to return the value as YYYY-MM-DD and I am struggling to work it out.

Yes, this is an assignment. No idea on the logic where we've been told to set one to Date and the other as LocalDate, other than to annoy me......

Any help appreciated.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
user10631180
  • 35
  • 1
  • 1
  • 4
  • 3
    If you have to return `YYYY-MM-DD`, then you're expected to return a `String`. Does your assignment say you must return `java.util.Date`? – ernest_k Jan 11 '20 at 06:16
  • You are asking the impossible. A `Date` cannot have a format. See for example [want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format](https://stackoverflow.com/questions/8745297/want-current-date-and-time-in-dd-mm-yyyy-hhmmss-ss-format). – Ole V.V. Jan 11 '20 at 13:51
  • The simple `StartDate.toString()` will give you a string in the format you asked for.But a `String`, not a `Date`. The `Date` class is poorly designed and long outdated anyway, so you may consider living with it. – Ole V.V. Jan 11 '20 at 13:53

4 Answers4

5

Please try this solution.

public static String getStartDate() {
    DateTimeFormatter oldPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
    DateTimeFormatter newPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime datetime = LocalDateTime.parse(new Date().toInstant().toString(), oldPattern);
    return datetime.format(newPattern);
}
Naveen
  • 346
  • 2
  • 10
3

Straightforward Answer - SimpleDateFormatter

As you state that the type returned by getStartDate must remain a Date. In this case, the most straightforward way to do this is to use the SimpleDateFormat class:

You can pass the date into a SimpleDateFormatter:

SimpleDateFormat iso_8601_formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(iso_8601_formatter.format(getStartDate());

More detailed information can be found at this blog post.

Best Practice Answer - Use java.time

As noted by Ole V.V., if it becomes possible to refactor the code, it would be best to unify the codebase around java.time instead of mixing that API with java.util.Date. This can be accomplished with a DateTimeFormatter

DateTimeFormatter iso_8601_formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate start = StartDate.atStartOfDay();
System.out.println(start.format(iso_8601_formatter));

Note that DateTimeFormatter supplies the constant DateTimeFormatter.ISO_LOCAL_DATE for printing values in ISO-8601 format.

More information about the improvements made in the new API can be found in this article.

  • @user10631180 you are actually accepted an answer, which is duplicate of another one, posted earlier. I recommend you to take a look at another, since it is more readable (which is essential in production). You should not build long callback chains like `println(simpleDateFormat.format(getStartDate());` – Steyrix Jan 11 '20 at 06:50
  • Excuse me if my comment looks harsh, I just wanted to add an advice to the answer – Steyrix Jan 11 '20 at 06:51
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jan 11 '20 at 13:49
  • 1
    @Ole V. V. The question specifically stated that the class had to remain a Date. However, I have updated my post to recommend that the swtich be made where possible. – Skyler Ferris Jan 12 '20 at 18:25
  • @Steyrix We have a difference of opinion here. I have worked with multiple projects where reading code is difficult due to the amount of vertical space it takes up - jumping back and forth through the file becomes cumbersome. In this particular example, the variable names don't add much value (in fact, the name `date` is misleading since it appears to specify a type). Having 1 variable is a reasonable tradeoff between the complexity of the line and the amount of vertical space the code takes. – Skyler Ferris Jan 12 '20 at 18:26
1

I think you can try this to get the date value as "yyyy-MM-dd"

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
    public static void main(String[] args) {
        String pattern = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

        String date = simpleDateFormat.format(new Date());
        System.out.println(date);
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Satya Dev Yadav
  • 143
  • 3
  • 13
  • The correct pattern is `yyyy-MM-dd`, not `YYYY-MM-DD` – Mark Rotteveel Jan 11 '20 at 12:23
  • Doesn't matter, It gives flexibility and work in both cases. You can check it ! – Satya Dev Yadav Jan 11 '20 at 12:37
  • 1
    It definitely matters: for example printing 2019-12-31 using YYYY when in - for example - The Netherlands, will print 2020, because YYYY is the week-year, not the calendar-year, and 2019-12-31 falls in week 1-2020. And printing that date with DD will result in 365, because DD is the day-in-year, not the day-in-month. So printing 2019-12-31 using YYYY-MM-DD prints 2020-12-365, while yyyy-MM-dd results in the correct 2019-12-31. – Mark Rotteveel Jan 11 '20 at 12:43
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jan 11 '20 at 13:50
  • OK, I will keep that in mind, Thanks for your suggestion – Satya Dev Yadav Jan 11 '20 at 17:54
0

While returning an instance of java.util.Date, you cannot format it. It will always be returned as a Date object. In case you want it in string,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(new Date());

where new Date() is todays date, whatever date object you put, the sdf object (java.text.SimpleDateFormat) will do that. You can refer to java 8 docs of SimpleDateFormat for more.