SimpleDateFormat - Timezone - SystemTime troubles

Hi there,
I don't understand why the following little class produces the results it produces:
input timestamp = 1097670920739
formatted String #1 = 2004-35-13T14:35:20+0200
result timestamp = 1073997320000
formatted String #2 = 2004-35-13T13:35:20+0100
I would have expacted seeing two times the same timestamp and two times the same formatted String and have no idea where the problem is. Please Help.
Thanks
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
public class TestDates {
private TestDates() {}
public static void main(String[] args) {
String input = "1097670920739";
// 1. Get Date-String from java-timestamp
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ssZ", Locale.GERMANY );
long timestamp1 = ( new Long( input ) ).longValue();
Date date1 = new Date( timestamp1 );
String string1 = formatter1.format( date1 );
// 2. Get back java-timestamp from Date-String
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ssZ", Locale.GERMANY );
Date date2 = null;
try { date2 = formatter2.parse( string1 ); } catch ( java.text.ParseException e ) {}
long timestamp2 = date2.getTime();
// 3. Get back Date-String form temp java-timestamp
SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ssZ", Locale.GERMANY );
Date date3 = new Date( timestamp2 );
String string3 = formatter3.format( date3 );
System.out.println( "input timestamp = " + input );
System.out.println( "formatted String #1 = " + string1 );
System.out.println( "result timestamp = " + timestamp2 );
System.out.println( "formatted String #2 = " + string3 );
}

Well, one of your conversions isn't handling the daylight savings hour conversion properly.
Date date1 = new Date( timestamp1 );
Will convert the UTC / GMT long value into a date object for your default timezone on your pc.
Is your regional settings and timezone set up to German time on your pc ?
Sorry, haven't time to think this one through fully...
regards,
Owen

Similar Messages

  • How to Convert  GMT in EST timezone

    We are comunicating with a system,which send date and time in this format - GMT Date and time in YYYYMMDDHHMISS where HH is 24 hour format.Our server has EST (US) time zone. Now I have to validate if the received time stamp from our client is with in +/- 5 minutes, we need to allow him to do some operation.So How can I compare the time stamps in GMT and EST.Which java classes I need to use to accomplish it, any code snippet wil be hepful
    thanks in advance
    pary

    Try this it may help you.
              Date date = new Date();
             DateFormat estFormat = new SimpleDateFormat();
             DateFormat gmtFormat = new SimpleDateFormat();
             TimeZone gmtTime = TimeZone.getTimeZone("GMT");
             TimeZone estTime = TimeZone.getTimeZone("EST");
             estFormat.setTimeZone(gmtTime);
             gmtFormat.setTimeZone(estTime);
             System.out.println("GMT Time: " + estFormat.format(date));
             System.out.println("EST Time: " + gmtFormat.format(date));Result::
    GMT Time: 10/5/05 5:37 AM
    EST Time: 10/5/05 1:37 AM

  • More trouble with timezones when storing value in TS WITH LTZ

    Using Oracle 9i, JDK 1.4.2.
    I have a script using the Jakarta Jelly framework to initialize my db. When I run the script, I want to set the current time in several "TIMESTAMP WITH LOCAL TIME ZONE" columns.
    Before the time change, the following excerpt from my script was working fine.
    <j:new className="java.util.Date" var="now" />
    <j:new className="java.text.SimpleDateFormat" var="format">
    <j:arg type="java.lang.String" value="dd-MMM-yyyy hh.mm.ss.SS a Z"/>
    </j:new>
    <j:set var="ts"
    value="cast(cast('${format.format(now)}' as timestamp with time zone) as timestamp with local time zone)"/>
    The "Z" in the date/time format produces a 3-letter timezone abbreviation, like "PST" or "PDT".
    Before the time change, I was getting "PST" from this, and the code was working fine. When the time change hit, I discovered that Oracle doesn't grok "PDT" (I found info on the internet about this, but I can't find it right now). I thought for a short time on this, and I changed "Z" to "z", which results in "-0700" instead of "PDT". This appeared to work fine. It didn't fail, at least.
    However, what I discovered today is that Oracle gets confused by it. It recognizes that as a timezone offset, but it only "half" understands this. When I view the value in SQLDeveloper, it shows a time value 7 hours before the current time, instead of the correct current time as it used to.
    I also tried hardcoding a date string, using "US/Pacific", and Oracle groks that, but of course, it doesn't know to use daylight savings time.

    that makes sense because you are setting the sessionAttribute at the wrong time.. see you are passing the paramater from index to shop, so you really need to set the sessionAttribute in the index page so it is always available in the shop page.
    hope that helps...you will always have this problem when refreshing because when you refresh the value from "customer" is not being passed again.....

  • SimpleDateFormat and TimeZone; is: +0200 but must be +02:00

    Hello,
    running this code ...
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
    System.out.println(sdf.format(new Date()));... outputs this line as expected ...
    2008-07-24T18:59:58+0200... but what i actually need is ...
    2008-07-24T18:59:58+02:00Note the additional colon in the time zone output: +02*:*00. How to get that format as described in http://www.w3.org/TR/NOTE-datetime ?
    Thanks!

    nclow wrote:
    CapM wrote:
    Yes, but it also added a "GMT", which is not allowed by the remote side (i need to format XML that follows certain restrictions).Then your problem has just become a bit larger. Read the difference between the z and the Z symbol in the sdf API documentation. What will you do when your timezone output is "EDT" as it is for me? You can't put a colon in that. You may have to do further parsing with a Z symbol to eliminate text from that output and just keep the numbers. You might want to just do a new SimpleDateFormat("Z") and then pass that to a custom parser which will manipulate it according to your requirements, then append it later.Well, i guess that one is graceful and pragmatic enough. Thanks for your suggestions @ all!

  • SimpleDateFormat and TimeZone problem

    Hi all, I know there have been a lot of questions
    concerning this topic, but I've looked over a lot
    of messages and I think I've used all ideas provided,
    yet still I can't fix my problem.
    My problem concerns parsing a date from a HTTP
    packet. I use the following code:
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss zzz");
    sdf.setTimeZone(TimeZone.getDefault());
    Date date = sdf.parse(packet.substring(exp_pos+9, endline));Most of the time this code works perfectly, however
    from time to time the parse result is 12 hours of.
    Instead of 14h the result is 2h. HTTP dates use a
    24 hour time.
    I'm using the JVM by Blackdown, version 1.3.1 on
    Debian Linux 2.2.18. The timezone is configured
    correctly in my os. I'm in GMT+1.
    I'm not sure if this is a bug or if I have done something
    wrong.
    Any help would be greatly appreciated.
    Peter

    Looks to me that your time format with lower-case "hh" tells it to use the 12-hour, not 24-hour format, and you're not including the am/pm indicator. So it's doing just what you're telling it to do. If you want 24-hour format, use "HH" instead of "hh".

  • Parsing Timezones with SimpleDateFormat

    String FLASH_DATE_FORMAT = "EEE MMM d HH:mm:ss zZ yyyy";
    DateFormat dateParser = new SimpleDateFormat(FLASH_DATE_FORMAT);
    Date date = dateParser.parse("Tue May 10 00:00:00 GMT+0000 2005");I get the message "Unparseable date: "Tue May 10 00:00:00 GMT+0000 2005"".
    What's wrong?
    I don't think it likes the fact that the timezone (GMT) and adjustment (+0000) are immediately next to oneanother, because if I add a space to the pattern and the date, it works fine.

    You shouldnt be setting GMT timezones in your format String.
    //pseudo code
    SimpleDateFormat dateParser = new SimpleDateFormat("format string);
    dateParser.setTimeZone("Your timezone id")//pls look at java.util.TimeZone to obtain the correct timezone id);
    dateParser.parse("date string");Cheers,
    ram.

  • Parsing TimeZone using simpleDateFormat

    Hi,
    I have a String: "14/03/2007 21:07:07 Europe/London" which i want to convert into java.sql.Date.
    Any ideas whats the simplest approach?
    I have tried using the SimpleDateFormat( "dd/MM/yyyy hh:mm:ss z" ) but then it fails to parse.
    Seems I am missing something simple here :)
    Ta,

    This smells like a bug in the parse method.
    If you have a date + time + valid timezone string, then the method should be able to create a Date - otherwise, how does one get the correct Date?
    Running the program below resulted in this output and unparseable error (changing the timezone to "PST" runs ok.)
    ***timezone dump = sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,
    lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,
    startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
    ***timezone id = America/Los_Angeles
    ***data to be parsed = 14/03/2007 21:07:07 America/Los_Angeles
    java.text.ParseException: Unparseable date: "14/03/2007 21:07:07 America/Los_Angeles"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at Time.main(Time.java:22)
    The parse method in DataFormat calls an abstract method which is implemented in SimpleDateFormat. That code is convoluted (!), but certainly appears to me to be trying to match against timezone strings like "America/Los_Angeles".
    Other opinions?
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    public class Time
        public static void main(String[] args)
            TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
            // The preceeding line is copied from the TimeZone API example code
            System.out.println("***timezone dump = " + tz);
            System.out.println("***timezone id = " + tz.getID());
            String parseMe = "14/03/2007 21:07:07 " + tz.getID();
            System.out.println("***data to be parsed = " + parseMe);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss zzzz" );
            try
                Date date = sdf.parse(parseMe);
            catch (ParseException ex)
                ex.printStackTrace();
    }

  • Trouble with dateTime if data has Timezone information

    I have a problem with inserting a document in a XMLType column. I get the following error message:
    ORA-01830: date format picture ends before converting entire input stringI did some searching and the problem is the element which is a dateTime with Timezone information. If the entry oraxdb:SQLType="TIMESTAMP WITH TIME ZONE" is added everything is correct.
    The problem is that we dont want to edit the XSD because it was standardized. Is there another way to get around this error ( e.g. parameter or column definition, ... ) ?
    Greeting
    Alex
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE 11.2.0.1.0 Production
    TNS for IBM/AIX RISC System/6000: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production

    XSL is probably a bit overkill, you could do stuff like the following as well
    SQL> declare
      V_FILENAME  VARCHAR2(700) := 'CMFXML.SWIFT.MT544.xsd';
      V_XMLSCHEMA XMLTYPE := xmltype(bfilename('XMLDIR',V_FILENAME),nls_charset_id('AL32UTF8'));
      2    3    4  begin
      5          -- dbms_xmlschema_annotate.addXDBNamespace(V_XMLSCHEMA);
      6          dbms_xmlschema_annotate.setDefaultTable(V_XMLSCHEMA,'CMFXML','CMFXML_MT544_TABLE');
      7          dbms_xmlschema_annotate.DISABLEDEFAULTTABLECREATION(V_XMLSCHEMA);
      8
      9          select insertChildXML
    10           (
    11                   V_XMLSCHEMA,
    12                   '//xsd:element[@type="TIndicator-22F-01"]',
    13                   '@xdb:SQLInline',
    14                   'false',
    15                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    16                 )
    17            into V_XMLSCHEMA
    18            from dual;
    19
    20          select insertChildXML
    21           (
    22                   V_XMLSCHEMA,
    23                   '//xsd:element[@type="TAmount-19A-01"]',
    24                   '@xdb:SQLInline',
    25                   'false',
    26                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    27                 )
    28            into V_XMLSCHEMA
    29            from dual;
    30
    31          select insertChildXML
    32           (
    33                   V_XMLSCHEMA,
    34                   '//xsd:element[@type="TDate-98A-01"]',
    35                   '@xdb:SQLInline',
    36                   'false',
    37                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    38                 )
    39            into V_XMLSCHEMA
    40            from dual;
    41
    42          select insertChildXML
    43           (
    44                   V_XMLSCHEMA,
    45                   '//xsd:element[@type="TRate-92A-01"]',
    46                   '@xdb:SQLInline',
    47                   'false',
    48                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    49                 )
    50            into V_XMLSCHEMA
    51            from dual;
    52
    53          select insertChildXML
    54           (
    55                   V_XMLSCHEMA,
    56                   '//xsd:element[@type="TFlag-17B-01"]',
    57                   '@xdb:SQLInline',
    58                   'false',
    59                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    60                 )
    61            into V_XMLSCHEMA
    62            from dual;
    63
    64          select insertChildXML
    65           (
    66                   V_XMLSCHEMA,
    67                   '//xsd:element[@type="TQuantityOfFinancialInstrument-36B-01"]',
    68                   '@xdb:SQLInline',
    69                   'false',
    70                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    71                 )
    72            into V_XMLSCHEMA
    73            from dual;
    74
    75          select insertChildXML
    76           (
    77                   V_XMLSCHEMA,
    78                   '//xsd:element[@type="TReference-20C-01"]',
    79                   '@xdb:SQLInline',
    80                   'false',
    81                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    82                 )
    83            into V_XMLSCHEMA
    84            from dual;
    85
    86  select insertChildXML
    87           (
    88                   V_XMLSCHEMA,
    89                   '//xsd:element[@type="TParty-95PQR-01"]',
    90                   '@xdb:SQLInline',
    91                   'false',
    92                   'xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xsd="http://www.w3.org/2001/XMLSchema"'
    93                 )
    94            into V_XMLSCHEMA
    95            from dual;
    96
    97
    98          dbms_xmlschema_annotate.setOutOfLine(V_XMLSCHEMA,'element','ReceiveFreeConfirmationType','TwoLegTransactionDetails','MT544_TWO_LEG_TRANS_TABLE');
    99          dbms_xmlschema_annotate.setOutOfLine(V_XMLSCHEMA,'element','ReceiveFreeConfirmationType','TradeDetails','MT544_TRADE_DETAILS_TABLE');
    100          dbms_xmlschema_annotate.setOutOfLine(V_XMLSCHEMA,'element','TTradeDetails','FinancialInstrumentAttributes','MT544_FIN_INST_ATTRS_TABLE');
    101
    102    dbms_xmlschema.registerSchema
    103    (
    104      schemaurl       => V_FILENAME,
    105      schemadoc       => V_XMLSCHEMA.getClobVal(),
    106      local           => TRUE,
    107      genTypes        => TRUE,
    108      genBean         => FALSE,
    109      genTables       => TRUE
    110    );
    111  end;
    112  /

  • TImezone trouble...

    I started working on a new project with a unit test that tested the DST change in 2007. The test was good, but my machine did not pass. I am running ubuntu 9.04 updated and using various jdk's, but 1.6.0_16 specifically for this project. I updated my tzdata, I removed and reinstalled my jdk. I checked the jdk with the tzupdater.jar version: tzdata2009k. My /etc/localtime was a copy of /usr/share/zoneinfo/America/New_York. I reconfigured my timezone from the GUI and from the commandline. That is when I decided enough was enough and I read the native c code that pulls the tz data from the OS. First it looks in /etc/sysconfig/clock where it finds it fine, like on my REHL5.3 box.
    # The ZONE parameter is only evaluated by system-config-date.
    # The timezone of the system is defined by the contents of /etc/localtime.
    ZONE="America/New_York"
    UTC=true
    ARC=falseNext it checks /etc/localtime to see if it is a symlink (which nobody does any more). If it is, it parses the link and determines the tz locale.
    Finally when all that fails it recursively searches /usr/share/zoneinfo for a file that first is the same size as /etc/localtime, and then secondly is the same using binary compare. Once found, the path is parsed and the tz locale is returned. Java does not use the os version, it then uses its own version in ${JAVA_HOME}/jre/lib/zi. On my updated ubuntu 9.04 distro /usr/share/zoneinfo/SystemV/EST5EDT is the same as /usr/share/zoneinfo/America/New_York
    jjv6@qubit:/$ diff /usr/share/zoneinfo/America/New_York usr/share/zoneinfo/SystemV/EST5EDT
    jjv6@qubit:/$ BUT in java they differ.
    jjv6@qubit:/$ diff /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/America/New_York /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/SystemV/EST5EDT
    Binary files /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/America/New_York and /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/SystemV/EST5EDT differ
    jjv6@qubit:/$ I only assume that the OS version is correct, as that makes the most sense, but holey crap, you recursively search for a file that is the same and pick it. Just so happens that my SystemV inode comes before my America inode, don't know why, dont' really care. I'm worried because this is the best we can to, in 2009, for having a standard process for determining tz locale. We need to be better.
    jjv6@qubit:/$ cat /etc/timezone
    America/New_York
    jjv6@qubit:/$ Can we get someone to revamp this c code and check a few more "standard" spots before we go completely off the deep end and assume /etc/localtime == /usr/share/zoneinfo/county/locale.

    I started working on a new project with a unit test that tested the DST change in 2007. The test was good, but my machine did not pass. I am running ubuntu 9.04 updated and using various jdk's, but 1.6.0_16 specifically for this project. I updated my tzdata, I removed and reinstalled my jdk. I checked the jdk with the tzupdater.jar version: tzdata2009k. My /etc/localtime was a copy of /usr/share/zoneinfo/America/New_York. I reconfigured my timezone from the GUI and from the commandline. That is when I decided enough was enough and I read the native c code that pulls the tz data from the OS. First it looks in /etc/sysconfig/clock where it finds it fine, like on my REHL5.3 box.
    # The ZONE parameter is only evaluated by system-config-date.
    # The timezone of the system is defined by the contents of /etc/localtime.
    ZONE="America/New_York"
    UTC=true
    ARC=falseNext it checks /etc/localtime to see if it is a symlink (which nobody does any more). If it is, it parses the link and determines the tz locale.
    Finally when all that fails it recursively searches /usr/share/zoneinfo for a file that first is the same size as /etc/localtime, and then secondly is the same using binary compare. Once found, the path is parsed and the tz locale is returned. Java does not use the os version, it then uses its own version in ${JAVA_HOME}/jre/lib/zi. On my updated ubuntu 9.04 distro /usr/share/zoneinfo/SystemV/EST5EDT is the same as /usr/share/zoneinfo/America/New_York
    jjv6@qubit:/$ diff /usr/share/zoneinfo/America/New_York usr/share/zoneinfo/SystemV/EST5EDT
    jjv6@qubit:/$ BUT in java they differ.
    jjv6@qubit:/$ diff /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/America/New_York /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/SystemV/EST5EDT
    Binary files /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/America/New_York and /usr/lib/jvm/jdk1.6.0_16/jre/lib/zi/SystemV/EST5EDT differ
    jjv6@qubit:/$ I only assume that the OS version is correct, as that makes the most sense, but holey crap, you recursively search for a file that is the same and pick it. Just so happens that my SystemV inode comes before my America inode, don't know why, dont' really care. I'm worried because this is the best we can to, in 2009, for having a standard process for determining tz locale. We need to be better.
    jjv6@qubit:/$ cat /etc/timezone
    America/New_York
    jjv6@qubit:/$ Can we get someone to revamp this c code and check a few more "standard" spots before we go completely off the deep end and assume /etc/localtime == /usr/share/zoneinfo/county/locale.

  • Strange result of SimpleDateFormat.parse()

    Hi,
    I'm having trouble with the parse data function as it does not return the correct hour.
    Here is what I'm doing:
    Date nullDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse("1900-01-01T00:00:00-0000");I would now expect nullDate to be Mon Jan 01 00:00:00 CET 1900
    But instead, it is Mon Jan 01 00:09:21 CET 1900
    Personally I cannot think of a reason why the time is not 0.
    Any ideas?

    I don't see the problem you see. What version of Java on what OS and in what time zone?
    P.S. I would certainly set the time zone for the parser i.e.
           SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            parser.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date nullDate = parser.parse("1900-01-01T00:00:00-0000");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
            System.out.println(formatter.format(nullDate));On my Ubuntu 10.04 using JDK 1.6.0_20 in London (currently GMT) time zone I get
    1900-01-01 00:00:00 GMT

  • Get user's locale / Timezone

    Hi
    I am developing Customized Calendar jsp on OCS by
    only using Calendar API(calendarlet.jar) not using Portal API.
    I have problem to get User's Locale/TimeZone that User had set in Preference.
    Calendar API Select and Display baesed on UDT
    CASE :
    " User had choice certain TimeZone in Preference
    then Calendar PKG display time based on User Selected Time-Zone
    but Customized Calender JSP displayed time on UCT "
    How can I get locale/TimeZone that user had set in Calendar Preference ?
    (Using calendar API)

    That's odd. You say that java.util.Date doesn't have
    any timezone in it, but when I insert a breakpoint
    and look at the contents of the object it has a
    sun.util.calendar.BaseCalendar and that has a
    timezone in it. Date != Calendar. A Date is just a long. Like I said, right this second, if you, I, somebody in Chicago, somebody in NY, somebody in London, and somebody in Tokyo all create a Date, the long will be the same for all of us--number of millis since 1/1/1970 00:00:00 GMT. (Note that this does NOT meant that Date "has" a TZ. It does not.) The TZ comes when a String is created from the Date.
    I always just assumed that that
    timezone must be what I was having trouble with.
    As for the DB, I assumed that mysql was timezone
    agnostic, and simply took times in and spit them out
    exactly the same. Are you saying that when I put 8AM
    in, if a person in england had that database that
    same value would read midnight? If so, is there any
    way to make it timezone neutral? It's complicating
    things.It is TZ-agnostic. You're overcomplicating it.
    // In LA, I do
    date = new Date(); // Ignore util.Date/sql.Date/Timestamp distinction for now
    S.o.p(date); // prints out Thu., 9:53 a.m. PDT
    ps = con.prepareStatement("insert into whatever values (?)");
    ps.setDate(1, date);
    ps.executeUpdate();
    // In London, you do
    rs = execute("select * from whatever"); // yeah, I'm fudging the jdbc stuff. Just lazy
    rs.next();
    date = rs.getDate(1); // this Date wraps the same long as my original in LA
    S.o.p(date); // prints out Thu., 5:53 p.m. BST or whatever
    sdf = new SimpleDateFormat(some format);
    sdf.setTimeZone(new york);
    S.o.p(sdf.format(date)); // prints Thu., 12:53 p.m. EDTThe DB stores "N millis since the epoch", or something equivalent. My LA Java and your London Java read that value and interpret it as the same point in time. When we print it, it converts to the appropriate TZ.

  • SimpleDateFormat / Daylight Savings time issue in 1.5.0_11 ?

    I am having trouble with SimpleDateFormat.format(), possibly due to Daylight Savings Time, but I can't figure it out.
          import java.text.*;
          import java.util.*;
          public class Test {
            public static void main(String[] args) throws Exception{
              SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd z yyyy");
              Date date = dateFormat.parse("Tue April 13 CDT 2007");
              System.out.println(dateFormat.format(date));
              System.out.println(date.toString());
              SimpleDateFormat dateFormat2 = new SimpleDateFormat("MMMM dd, yyyy");
              System.out.println(dateFormat2.format(date));
          }I am in the CDT time zone.
    If I run this code on JRE 1.5.0_04-b05, I get:
    Fri Apr 13 CDT 2007
    Fri Apr 13 00:00:00 CDT 2007
    April 13, 2007This is what I expect. But, if I run this code on JRE 1.5.0_11-b03, I get:
    Fri Apr 13 CDT 2007
    Thu Apr 12 23:00:00 GMT-06:00 2007  
    April 12, 2007I don't understand why, the time calculated to be an hour off, since my time zone and locale are the same as that of the input string?
    I thought this could be a DST issue, but a) both dates are in DST, and b) I tried applying the fix to the Java 5 DST bug, on the off chance it would help. but it did nothing. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6530336
    I'm stumped. Can anyone help?
    Thanks,
    Ed

    It looks like the problem is that Java doesn't have my timezone correct after all.
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd z yyyy");   
    System.out.println(dateFormat.getTimeZone());    prints:
    sun.util.calendar.ZoneInfo[id="GMT-06:00",offset=-21600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
    ...which is wrong. It should be dstSavings=3600000,useDaylight=true.
    So, one SimpleDateFormatter has CDT as its timezone, and the other has CST as its timezone. This changes the time from midnight on one day to 11 pm on the previous day, causing the wrong date to be shown.
    This workaround gives the date I want, the original date at its (not my) timezone.
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd z yyyy");   
        Date date = dateFormat.parse("Tue April 13 CDT 2007");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("MMMM dd, yyyy");
        dateFormat2.setTimeZone(dateFormat.getTimeZone());
        System.out.println(dateFormat2.format(date));Now if I can coerce Java to give me my correct local time zone, I'll be set.

  • How to set Timezone in a date object

    Hi,
    I need to write a method setTimeZone(Date d,TimeZone t) which should take a Java.util.Date and a Timezone object and set the time zone to the date object.
    for example...
    Date d=new Date();
    TimeZone tz=TimeZone.getTimeZone("PST");
    //should print the timezone as EDT because the current system timezone is EDT
    System.out.println(d);
    setTimeZone(d,tz);
    //should print the timezone as PST
    System.out.println(d);
    public void setTimeZone(Date d,TimeZone tz){
    Calendar c=Calendar.getInstance(tz);
    c.setTime(d);
    c.setTimeZone(tz);
    d=c.getTime();
    System.out.println("Timezone in calendar is "+c.getTimeZone().getDisplayName());
    But today is still showing up EDT timezone and Timezone in calendar is shown as PST.The new timzone is not aplied to date object @ d=c.getTime();
    statement.
    Could any one please help me...
    Edited by: mchepuri on Apr 10, 2009 7:27 PM
    Edited by: mchepuri on Apr 10, 2009 7:29 PM

    Dates don't have any concept of time zones. Think of a Date as a wrapper for a long.
    Use SimpleDateFormat. Read the javadocs for some useful methods.

  • How to specify timezone in quartz scheduler

    Hi,
    I want to initiate a job at a particular time - 6 AM EST every Monday. The cron expression can help me do "6 AM every Monday" part, but not the EST part. How do I specify a timezone. I could not find any examples pertaining to doing this in quartz used in a web application. I found some links that talked about doing this in spring framework - http://forum.springsource.org/archive/index.php/t-16381.html
    My web.xml currently looks like this:
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
    <description>Empty web.xml file for Web Application</description>
    <!--servlet>
    <servlet-name>QuartzInitializer</servlet-name>
    <servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
    <param-name>config-file</param-name>
    <param-value>bpel_quartz.properties</param-value>
    </init-param>
    </servlet-->
    <servlet>
    <servlet-name>BPELSchedulerServlet</servlet-name>
    <servlet-class>com.otn.samples.BPELSchedulerServlet</servlet-class>
    <init-param>
    <param-name>cronExpr</param-name>
    <param-value>0 0 6 ? * MON</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>BPELSchedulerServlet</servlet-name>
    <url-pattern>/bpelschedulerservlet</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>35</session-timeout>
    </session-config>
    <mime-mapping>
    <extension>html</extension>
    <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
    <extension>txt</extension>
    <mime-type>text/plain</mime-type>
    </mime-mapping>
    </web-app>
    TIA
    Amit

    Thanks, I followed your suggestion and was able to make this work. Here is what I have done.
    In Web.xml, added a new init parameter, timezone.
    <servlet>
    <servlet-name>BPELSchedulerServlet</servlet-name>
    <servlet-class>com.otn.samples.BPELSchedulerServlet</servlet-class>
    <init-param>
    <param-name>cronExpr</param-name>
    <param-value>0 30 6 ? * MON</param-value> <!--Mondays 6:30amEST -->
    </init-param>
    <init-param>
    <param-name>timezone</param-name>
    <param-value>EST</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
    </servlet>
    then in the scheduler servlet,
    String cronExprFromWebXml = null;
    // Get the cron Expression as an Init parameter
    cronExprFromWebXml = getInitParameter("cronExpr");
    String timezone = getInitParameter("timezone");
    String cronExpr = convertCronExpr(cronExprFromWebXml,timezone);
    and I wrote a function in the same file,
    public String convertCronExpr(String inputCronExpr, String desiredTimezone)
    String outputCronExpr="";
    String[] inputCronArray = inputCronExpr.split(" ");
    String dateInDesiredFormat = inputCronArray[0]+":"+inputCronArray[1]+":"+inputCronArray[2]+":"+desiredTimezone;
    String dateInServerFormat;
    DateFormat genFormat = new SimpleDateFormat("s:m:k:z");
    Date specifiedTime;
    try
    specifiedTime = genFormat.parse(dateInDesiredFormat);
    genFormat.setTimeZone(TimeZone.getDefault());//This gets the server timezone
    dateInServerFormat = genFormat.format(specifiedTime);
    String[] outputCronArray = dateInServerFormat.split(":");
    outputCronExpr = outputCronArray[0]+" "+outputCronArray[1]+" "+outputCronArray[2]+" "+inputCronArray[3]+" "+inputCronArray[4]+" "+inputCronArray[5];
    System.out.print("inputCronExpr "+inputCronExpr);
    System.out.println(" --- In "+desiredTimezone);
    System.out.print("outputCronExpr "+outputCronExpr);
    System.out.println(" --- In soa suite timezone,"+TimeZone.getDefault().getDisplayName());
    return outputCronExpr;
    catch (ParseException e)
    return inputCronExpr;
    ofcourse I havent done any error handling here, and the code really works only for the given situation (it would fail if we use other forms of the cron expression..)
    -Amit

  • How to convert date in one timezone to date in another timezone?

    Hi,
    I am building a web site which can be accessed by people across world in different timezones. I have a requirement to collect the data from the users in their respective timezones and convert it to the timezone in which the server is hosted before saving it. E.g. a user in "Kwajalein" timezone (GMT - 12) enters date as "10/23/2007 21:00", the time for the server which is hosted in indian timezone (GMT + 5.30) would be "10/24/2007 14:30". If I use the following program to convert the dates in these timezones it gives me wrong output.
    TimeZone tz = TimeZone.getTimeZone("Kwajalein");
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
    df.setTimeZone(tz);
    Date d = df.parse("10/23/2007 21:00");
    TimeZone tz1 = TimeZone.getTimeZone("Asia/Calcutta");
    df.setTimeZone(tz1);
    System.out.println("date in IST-->" + df.format(d));
    The output of this program is
    date in IST-->10/23/2007 14:30
    The formatter has changed the time component however it hasn't changed the date. It still appears as 23.
    Am I doing anything wrong here?
    Please pass your comments.
    Thanks,
    Shashi

    Please see the following link it may be helpfull to you
    1) http://forum.java.sun.com/thread.jspa?threadID=755558
    2) http://myhowto.org/java/36-all-about-locale-sensitive-time-processing-in-java/

Maybe you are looking for