-2

I have a problem on the java conversion of the dates. I have input a String, YYYYMMDD, that converts to long and by executing the code the output is wrong

try {
           //Current date to dd-mm-yyyy
            Date currentDate = new Date(20161205); //or 
            DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
            String strCurrentDate = df.format(currentDate);
            System.out.println("Date is " + strCurrentDate);
        } catch (Exception e) {
            System.out.println("Exception :" + e);
        }

The output is: 01-49-1970 why?? How can I solve the problem

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
oceano22
  • 463
  • 1
  • 5
  • 8
  • 2
    Please do not use the legacy `java.util.Date` class. You should instead use the appropriate class from the `java.time` package. – Joe C Feb 24 '18 at 22:53
  • What is your default time zone? The 49 in the output look weird. – Ole V.V. Feb 25 '18 at 09:15
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 25 '18 at 20:14

4 Answers4

1

Solution:

 Date currentDate = new Date(116,11,05);

Explanation:

You put single number as an argument of constructor of Date. If you take a look at list of available constructors of this class in Java API documentation here, you'll notice that the one taking long as argument will be chosen. As documentation states:

Date​(long date) - Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Instead of that, if you really need to use java.util.date package (java.time is considered as the right choice nowadays), consider using another constructor: Date​(int year, int month, int date). In that case, you should pass the following numbers as parameters:

Date currentDate = new Date(116,11,05);

This is because:

year - the year minus 1900.

month - the month between 0-11.

date - the day of the month between 1-31.

By the way, consider using java.time package instead of java.util as java.util.Date is now deprecated.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
1

you are doing it in the wrong way see if you want to change date from this formate yyyyMMdd to this formateyyyy-MM-dd

you have to to change your code a little bit

try {
//Current date to dd-mm-yyyy

DateFormat fromFormate = new SimpleDateFormat("yyyyMMdd");
DateFormat toFormate = new SimpleDateFormat("yyyy-MM-dd");

String dateToFormate = "20161205"; //or 
Date d=fromFormate.parse(dateToFormate);

System.out.println("Date is " + toFormat.formate(d));
} catch (Exception e) {
System.out.println("Exception :" + e);
}
FRe34
  • 105
  • 11
1

tl;dr

LocalDate.parse(
    "20161205", 
    DateTimeFormatter.BASIC_ISO_DATE
).format(
    DateTimeFormatter.ofPattern("dd-MM-uuuu")
)

05-12-2016

Why 01-49-1970?

I cannot reproduce your exact output so can explain most of it, not all. Probably you’ve confused a couple of your test examples and didn’t get 01-49-1970 from new Date(20161205). On my computer I got Date is 01-36-1970. It’s bad enough.

As others have pointed out, new Date(20161205) gives you a point in time a little more than 20 000 seconds after the epoch of January 1, 1970 00:00 UTC. In UTC the time is then 5:36:01.205 (AM) on January 1. The time in your time zone probably differs. There are time zones where the date is still December 31, 1969.

But this doesn’t seem to explain how you seem to get an output in the 49th month of 1970, or I in the 36th month. This is because you used lowercase mm in your format pattern string. mm is for minute of hour. Uppercase MM is for month. So the 36 I got matches the minutes in the 5:36:01. There are time zones where the minutes are not the same; but I couldn’t find a time zone where the minute of hour is 49 at this time, so your exact reported output I cannot explain.

How can I solve the problem?

As others have said too, use java.time, the modern Java date and time API. It is so much nicer to work with.

    LocalDate currentDate = LocalDate.of(2016, Month.DECEMBER, 5);

Or from a string:

    LocalDate currentDate 
            = LocalDate.parse("20161205", DateTimeFormatter.BASIC_ISO_DATE);

Format to your desired output:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    String strCurrentDate = currentDate.format(dtf);
    System.out.println("Date is " + strCurrentDate);

This prints

Date is 05-12-2016

As a bonus java.time will let you know through an exception if you happen to use mm instead of MM in the format pattern string above.

Link: Oracle Tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Tip: This particular formatting pattern in pre-defined in Java: [`DateTimeFormatter.BASIC_ISO_DATE`](https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html#BASIC_ISO_DATE). No need to define the pattern with `ofPattern`. – Basil Bourque Feb 25 '18 at 20:15
0

Like @oceano22 said, there are newer/better date/time packages available. That said, the reason this is happening is because when you called new Date(20161205) the parameter that date constructor takes is NOT yyyyMMdd. According to the javadoc... "Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT."

So really you've created a date just 20 million milliseconds after the Unix epoch (Jan 1, 1970).

I've you're trying to get Dec 5, 2016 into a Date use df.parse("05-12-2016") with the SimpleDateFormat df you have defined.

You also likely want capital M's for month in your date format e.g. "dd-MM-yyyy" because lowercase m's are for minutes.

SpareTheRod
  • 476
  • 6
  • 13