Why SimpleDateFormat.format() and SimpleDateFormat.parse() are giving different time though setting only one TimeZone?

14,069

Solution 1

with Parse, you command the compiler to understand the given date in specific format. It understands and keep it in its own format and ready to give whatever format you want!

You are getting a output, which is a signal that you input date is parsed successfully. You dont have a control over the format of the date , that the variable is storing.

using format, you can convert the date to any desired format.

Simply Parse -> Reading ( I may read it in whatever manner and store in whatever manner I want) Format -> Write ( I will give you in the format you wanted )

Solution 2

dateFormat.format() will give you the output in given format and it will change the timezone to the one set in formatter. (eg dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));)

Whereas dateFormat.parse() assumes date is already in mentioned timezone and it will convert the date to your local timezone.

Share:
14,069
Deepu
Author by

Deepu

SOreadytohelp

Updated on June 04, 2022

Comments

  • Deepu
    Deepu almost 2 years

    I am trying to set the Timezone to the different country's timezone with help of SimpleDateFormat. SimpleDateFormat.format() returns correct current time of the given Timezone, but SimpleDateFormat.parse() returns local current time, I dont know why this is happening. Here is the my code -

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    System.out.println("Time1 : " + dateFormat.format(new Date()));
    System.out.println("Time2 : " + dateFormat.parse(dateFormat.format(new Date())));
    

    The Output is -

    Time1 : 2013-01-17 21:01:55
    Time2 : Fri Jan 18 10:30:55 IST 2013
    

    Time1 is the output of "America/Los_Angeles" and Time2 is the output of local(i.e. "Asia/Calcutta").

    I just want the current time of given Timezone in UTC Seconds format (ie Seconds since Jan 1, 1970).

    Why SimpleDateFormat.format() and SimpleDateFormat.parse() are giving different time though setting only one Timezone?

    Please help me.