Java – Android converting a string to a date changes the entire datetime

Android converting a string to a date changes the entire datetime… here is a solution to the problem.

Android converting a string to a date changes the entire datetime

Why is the output different?

   Date currentTrueSystemDate = Calendar.getInstance().getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kuwait"));
    String newConvertedDate = sdf.format(currentTrueSystemDate.getTime());
    System.out.println(newConvertedDate);
    try {
        Date newConvertedDate2 = sdf.parse(newConvertedDate);
        System.out.println(newConvertedDate2);
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage());
    }

Output:

 I/System.out: 27-Sep-2018 09:16:52
 I/System.out: Thu Sep 27 07:16:52 GMT+01:00 2018

The reason I converted “newConvertedDate” from string to date is that I want to use the .before and .after functions on it. I don’t understand why parsing a string to a date changes the time?

Solution

I don’t understand why parsing a string into date changes the time?

format() converts the date (without a time zone, which is the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC) to a string representation in the time zone, in which case you specify Kuwait.

So first time you get a string in Kuwait time zone and print it. This is just a string with no time zone information. But the time is Kuwaiti time.

Then use parse() to convert the string to a date, assuming the date is Kuwait time, because the SDF instances are the same. Now that the string is converted to a date, System.out.println prints it in your local time zone.

It should be noted that the two times are the same, only the time zone is different.

If you want the same time, you need to create a new instance of SimpleDateFormat and pass the date string to it. So it assumes that this is a local time zone date and parses to return a date that will give the same value again when printed. Note, however, that this date is different from the previous date, only the time is the same.

Do so

Date currentTrueSystemDate = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kuwait"));
        String newConvertedDate = sdf.format(currentTrueSystemDate.getTime());
        System.out.println(newConvertedDate);
        try {
            sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
            Date newConvertedDate2 = sdf.parse(newConvertedDate);
            System.out.println(newConvertedDate2);
        } catch (ParseException e) {
            System.out.println(e.getLocalizedMessage());
        }

Related Problems and Solutions