Android convert string to date changes the whole datetime

Aboodnet :

Why are the outputs are not the same?

   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 am converting "newConvertedDate" from a string to date because I want to use the .before and .after functions on it. I don't understand why parsing a string into date changes the time?

varunkr :

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

format() will convert a date(which has no timezone, it is the number of milliseconds passed since 1970-01-01 00:00:00 UTC) into a string representation in the timezone you specified, in this case, Kuwait.

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

Then you convert the string into a date using parse() which is assuming that the date is in Kuwait time as sdf instance is same. Now this string is converted to a date and System.out.println prints it in your local timezone.

Thing to note is that both time are same just different timezones.

If you want same times, you need to create a new instance of SimpleDateFormat and pass the date string to it. So that it would assume that this is the local time zone date and parse to return a date which when printed will again give the same value. However note that this date isn’t the same as previous one, just the time is same.

Do like this

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());
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99810&siteId=1