Converting Calendar Objects

I seem to be having a problem converting between to timezones. What I want to do is convert an ISO DateTime string of the format YYYY-MM-DDThh:mm:ss in the local timezone to a similar format string in UTC. I have posted the code below. When I input a value of 2003-08-25:11:50:00, what I expect back is 2003-08-25T21:50:00 (based on my current timezone), but I actually get 2003-08-25T01:50:00     public String convertLocalISODatetoUTC(String isoDate) {
     // Parse the date to get the local Date
     Date date = parseDate(isoDate);
     String convertedDate = null;
     if (date != null) {
         // Break the string into tokens
         StringTokenizer st = new StringTokenizer(isoDate, "-T:");
         String yyyy  = st.nextToken();
         String mn    = st.nextToken();
         String dd    = st.nextToken();
         String hh    = st.nextToken();
         String mm    = st.nextToken();
         String ss    = st.nextToken();
         int millsecondsOfDay = (Integer.parseInt(hh)*3600 +
                        Integer.parseInt(mm)*60 +
                        Integer.parseInt(ss))*1000;
         GregorianCalendar cal = new  GregorianCalendar ( Integer.parseInt(yyyy),
                                        Integer.parseInt(mn) - 1,
                                        Integer.parseInt(dd),
                                        Integer.parseInt(hh),
                                        Integer.parseInt(mm),
                                        Integer.parseInt(ss) );
         System.out.println(cal.toString()); // debug line
         TimeZone tz = TimeZone.getDefault();
         int tzOffset = tz.getOffset (cal.get(Calendar.ERA),
                          cal.get(Calendar.YEAR),
                          cal.get(Calendar.MONTH),
                          cal.get(Calendar.DAY_OF_MONTH),
                          cal.get(Calendar.DAY_OF_WEEK),
                          millsecondsOfDay);
         cal.roll(Calendar.MILLISECOND,
              cal.get(Calendar.MILLISECOND) + tzOffset);
         cal.setTimeZone(TimeZone.getTimeZone("UTC"));
         System.out.println(cal.toString());             // debug-line
         System.out.println(cal.getTime().toString());   // debug-line
         SimpleDateFormat df = new SimpleDateFormat(isoFormat);
         convertedDate = df.format(cal.getTime());
         System.out.println("Convertd date = "+convertedDate);  // debug line
     return convertedDate;
    }

BTW, private final String isoFormat  = "yyyy-MM-dd'T'HH:mm:ss";

Similar Messages

  • Convert a calendar object to a date object

    hi all...i use a calendar to select date and i want to convert the Calendar object returned to a date object ..how could i do that ?? i use the following lines of code but the Date object returned is not correct ..i mean it's not the one i chose from the calendar
    Date selectedDate=new Date();
    selectedDate=(calendar1.getTime());
    Any one could help....thank you

    Show us the code where you set the calendar to your desired value. Calendar1.getTime()
    should return the relevant date.

  • Convert Date Object to Calendar object

    Hi,
    I have a Date field in my webdynpro application, I need to to read this from my current context and convert the same to a Calendar field and pass it to my model.
    Calendar date = CalendarConverter.parseDate(req_date.toString());
    The above code gives me a null pointer exception.
    Can anyone suggest me the right way of converting a Date object to Calendar object?
    Ashwini.

    Ashwini,
    try to use the following code snippet:
    // get calendar and set your date object
    Calendar c = Calendar.getInstance();
    c.setTime( <YOUR_DATE_OBJECT> );
    // to manipulate the fields use this
    c.set(Calendar.MONTH, 1);
    // to manipulate retrieve a fields use this
    c.get(Calendar.MONTH);
    Hope that helps you.
    Sebastian Voss

  • Converting String to Calendar Object

    Hi,
    I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
    Fri Aug 17 01:56:40 GMT+05:30 1906
    Thanks in advance.
    Regards:
    Akash.

    Look at
    java.text.SimpleDataFormat

  • Convert Calendar to Java.sql.Date

    I seached for a solution for converting a Calendar-object to a java.sql.date for inserting it into a MySQL DB (DateTime). I know this question is a FAQ. The solution I found is the following code:
    java.sql.Date sqlDate =  new java.sql.Date(cal.getTime().getTime() );When i do a print of the sqlDate to the console I get: sqlDate: 2005-06-27
    But when I look into de DB I get the following date: 27/05/1905
    I know that in Java the months are starting from 0-�11 and that the years counting is starting from 1900. But I assume that the solution is not to just add the correct month and year manually. because I get a correct console-output. If I do this I get a correct DB Date, but a wrong console-date.

    II dont know if you found an answer but I needed a similar solution so I wrote a test program.
    Let me know if this solves the problem for you.
    import java.util.*;
    import java.sql.*;
    public class dateTest{
    public static void main(String args[]){
    // Step by step
    // Calendar rightNow = Calendar.getInstance();
    // java.util.Date today = rightNow.getTime();
    // long theTime = today.getTime();
    // java.sql.Date sDate = new java.sql.Date(theTime);
    // In one line
    java.sql.Date sDate = new java.sql.Date(Calendar.getInstance().getTime().getTime());
    System.out.println("sDate is: "+sDate.toString());
    }

  • Calendar object issues ... recompute remaining fields after change?

    Hello all. I'm doing date manipulation and arithmetic, but I'm running into a problem.
    I'm taking a date provided by a user and comparing it the current date. However, it's the month-end that I'm interested in.
    I'm already creating GregorianCalendar objects from each one, and doing the set on the DAY_OF_MONTH field to the value from getActualMaximum(DAY_OF_MONTH).
    The problem I'm having is that when dealing two dates from the same month, the two Calendar objects are >NOT< returning as EQUAL. After converting each object to a Date and running compareTo() (Side Bar: Why isn't compareTo() available in the Calendar class?) I'm not getting zero.
    I tried a toString() on the two objects, and I can see that some of the fields are not exact ... the time field is "?", WEEK_OF_YEAR, WEEK_OF_MONTH are different, etc. I can see the protected method complete() in the API, but attempts to execute them (gcCurrDate.complete()) yield compile errors stating the method is not visible.
    So how does one ask the system to fill in the remaining fields?
    Thanks!
    Steve

    According to the API docs for Calendar:
    "set(f, value) changes field f to value. In addition, it sets an internal member variable to indicate that field f has been changed. Although field f is changed immediately, the calendar's milliseconds is not recomputed until the next call to get(), getTime(), or getTimeInMillis() is made."

  • Calendar object without time

    Hi,
    I need to get a calendar object without displaying the time (hh:mm) field. Can smone help me with this??
    Thanks in advance

    Thanks for the replies..but my requirement is a
    calendar object which i need to set in one of the
    existing bean class set methods which takes in only a
    calendar object (I cant modify the method signature).
    I am pasting my code below..
    The situation is : I get data from database as a
    string read from a file which is then converted into
    a format yyyy-MM-dd using a simple date format. This
    returns a date object which i need to convert to
    calendar without showing the time fields. The prb is
    it is showing the GMT diff as default.
    public static Calendar dateString2Calendar(String s)
    throws ParseException {
    static SimpleDateFormat df = new
    SimpleDateFormat("dd-MMM-yy");
    static SimpleDateFormat df1 = new
    SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();          
    1 = null;
         Date d2 = null;
         String S1 = null;
         d1 = df.parse(s);
         S1 = df1.format(d1);
         d2 = df1.parse(S1);     
         cal.setTime(d2);     
         return cal;          
    Req output : 2004-09-07
    Current output : 2004-09-07+05:30
    00:00 also not allowed in the output :(The Calendar object represents a particular moment in time - it does not have a format and it always has a time portion. Do not use the toString() method to display it - if you use the System.out.println() method to display it, the toString() method is being still being called. Format the display using SimpleDateFormat as suggested.

  • Using expression to compare Calendar object

    Hi,
    I wonder if anyone has experience to use expression to compare Calendar object. Here is my case:
    Application {
    Calendar applicationDate;
    What I want is something like:
    expression.get("applicationDate").between(startDate, endDate);
    But it is seems not working this way.
    Any clue?
    Thanks
    Hao

    What error are you getting, in general this should work, however the Calendar will be printed/bound as a java.sql.Timestamp.
    If you require to use java.sql.Date if you just want the date portion of the Calendar.
    If your mapping for applicationDate sets the fieldClassification (i.e. is a TypeConversionMapping), then TopLink will automatically convert the Calendar value in the expression to the correct date type.

  • Is there a way to add event details using a calendar object vs. those dumb field entry boxes?

    I have switched from PC to Mac over a year and a half ago, and have been plagued with the "dumb" date entry boxes in iCal and now Reminders on the mac. For one, they don't show you the DAY OF WEEK for an event, it assumes you are parked on that day, but of course reality sets in and causes constant date changes for events. Picking a date in the future would be much more helpful if Apple followed some usability norms in iCal. For instance, if you are booking a flight online, those helpful little calendar objects pop up, and further, they are smart about "end dates and times" for events, knowing it can't be earlier than the start date. Apple iCal unfortunately always thinks you are creating an ALL DAY event, and when you change the start time, it creates the end time for the next day. Not very smart. Or is it me that is not very smart for constantly hawking every little data entry field for correctness. Why, oh why dear lord has Apple not given some usability attention to iCal on the mac??? At least match the interface of the iPhone with a nice little slot machine rolling control.
    Is there an add in?
    Is there hope that Apple will ever fix its lagging Mail and iCal apps on the Mac?
    Please advise. Or just offer a kind word of consolation if there is no hope for a better interface.

    In the future, Swing related questions should be posted in the Swing forum.
    The code you posted is of little use since it uses custom classes so we can't see the behaviour of your code.
    In general if you add a component to a Container at run time then you just use
    container.revalidate()
    This will invoke the LayoutManager and repaint the components in the container based on the new layout.

  • How can i convert an object to stream of chars or bytes?

    how can i convert an object to stream of chars or bytes?

    One way is the serialization mechanism. There are examples and explanations of it in the Java tutorial: http://java.sun.com/docs/books/tutorial/essential/io/serialization.html

  • How do i convert an object into a string?

    has said above, im trying to convert a object to a string.
    here is what i ahve so far:
    Object nodeInfo = node.getUserObject()

    RTFM
    Object o =...
    String str = o.toString();

  • How can I convert table object into table record format?

    I need to write a store procedure to convert table object into table record. The stored procedure will have a table object IN and then pass the data into another stored procedure with a table record IN. Data passed in may contain more than one record in the table object. Is there any example I can take a look? Thanks.

    I'm afraid it's a bit labourious but here's an example.
    I think it's a good idea to work with SQL objects rather than PL/SQL nested tables.
    SQL> CREATE OR REPLACE TYPE emp_t AS OBJECT
      2      (eno NUMBER(4)
      3      , ename  VARCHAR2(10)
      4      , job VARCHAR2(9)
      5      , mgr  NUMBER(4)
      6      , hiredate  DATE
      7      , sal  NUMBER(7,2)
      8      , comm  NUMBER(7,2)
      9      , deptno  NUMBER(2));
    10  /
    Type created.
    SQL> CREATE OR REPLACE TYPE staff_nt AS TABLE OF emp_t
      2  /
    Type created.
    SQL> Now we've got some Types let's use them. I've only implemented this as one public procedure but you can see the principles in action.
    SQL> CREATE OR REPLACE PACKAGE emp_utils AS
      2      TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
      3      PROCEDURE pop_emp (p_emps in staff_nt);
      4  END  emp_utils;
      5  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY emp_utils AS
      2      FUNCTION emp_obj_to_rows (p_emps IN staff_nt) RETURN EmpCurTyp IS
      3          rc EmpCurTyp;
      4      BEGIN
      5          OPEN rc FOR SELECT * FROM TABLE( CAST ( p_emps AS staff_nt ));
      6          RETURN rc;
      7      END  emp_obj_to_rows;
      8      PROCEDURE pop_emp (p_emps in staff_nt) is
      9          e_rec emp%ROWTYPE;
    10          l_emps EmpCurTyp;
    11      BEGIN
    12          l_emps := emp_obj_to_rows(p_emps);
    13          FETCH l_emps INTO e_rec;
    14          LOOP
    15              EXIT WHEN l_emps%NOTFOUND;
    16              INSERT INTO emp VALUES e_rec;
    17              FETCH l_emps INTO e_rec;
    18          END LOOP;
    19          CLOSE l_emps;
    20      END pop_emp;   
    21  END;
    22  /
    Package body created.
    SQL>Looks good. Let's see it in action...
    SQL> DECLARE
      2      newbies staff_nt :=  staff_nt();
      3  BEGIN
      4      newbies.extend(2);
      5      newbies(1) := emp_t(7777, 'APC', 'CODER', 7902, sysdate, 1700, null, 40);
      6      newbies(2) := emp_t(7778, 'J RANDOM', 'HACKER', 7902, sysdate, 1800, null, 40);
      7      emp_utils.pop_emp(newbies);
      8  END;
      9  /
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM emp WHERE deptno = 40
      2  /
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7777 APC        CODER           7902 17-NOV-05       1700
            40
          7778 J RANDOM   HACKER          7902 17-NOV-05       1800
            40
    SQL>     Cheers, APC

  • Hello, 2 questionss here is it possible or is there a way to convert all object s outlines in all frames to fills at once and not frame by frame? and why sometimes erases the outline instead of converting it to fill?

    Hello, 2 questionss here>is it possible or is there a way to convert all object s outlines in all frames to fills at once and not frame by frame? and why sometimes erases the outline instead of converting it to fill?

    Hello, 2 questionss here>is it possible or is there a way to convert all object s outlines in all frames to fills at once and not frame by frame? and why sometimes erases the outline instead of converting it to fill?

  • Urgent. Need help in the Calendar Object.

    Hello developers, best regards!
    Well my problem is that i'm facing a fact that i need a calendar object just like that one when u click the time down there in the taskbar, i need to embedd it in my java windows application.
    To be more clear, if u're familiar with the Visual Basic.NET environment, just the kind of calendars that i need is found there, in which it displays a small box which i can select the months, and accordingly i can select the specific date i need.
    Please i need your help so much.
    Thank you in advance.

    [url http://www.google.co.uk/search?hl=en&q=jcalendar&meta=]click

  • Printing Date with Calendar Object

    I am trying to print the current date of a calender object in a mm/dd/yyyy format.
    When I call system.out.println(now.getInstance()); and scroll through the console, it shows DAY_OF_MONTH=29, YEAR=2006, MONTH=6 for July 29, 2006. I realize months are zero based, so month is really 7. My question is, why does:
    System.out.println(now.MONTH + " " + now.DAY_OF_MONTH + " " + now.YEAR);
    print 2 5 1.
    Logic tells me it should print 6 29 2006.
    I have searched previous posts, and couldn't find one that answers my question. How do I take a Calendar object and print its current set date?

    My question is, why does:My question is: why do you care how a Calendar stores its data? If you want to print it, get a Date instance from it and run it through a SimpleDateFormat to get a String representation of the date.
    Don't mix up data and presentation.
    And to answer your question: you don't print the Calendar's date attributes, but the values of some static constants.

Maybe you are looking for

  • Changed number format in vs 2008 versus crystal report format

    I am using Crystal report designer  11.0.0.1.282  and I am able to see the numbers in the format I want . example is the year 2012,2013, etc. I don't want any decimal  point to be applied to this like 2013.00 because it is just the year and it should

  • Validation of a field in select statement

    In selection screen, skunag(vbrk-kunag) and swerks(vbrp-werks) fields are there.these two fileds are obligatory. If skunag field values start with 'P'.I have to remove the initial 'P' in that values,because I have to validate that field with ztable-k

  • IPod plus in but not able to run.

    I plug in my iPod touch and the following message comes up: "This iPod cannon be used because the apple mobile device service is not started" Any ideas?

  • New sky+hd box wont allow recordings

    I got a used Sky+hd box from a friend and set it up fine and paired my card etc. but i wont allow me to record or playback anything. I currently have all the Sky channels and multiroom as this is an upgrade to my original skyHd box. Any help on getti

  • General File Sharing Via iCloud

    Does anyone know if Apple is planning on offering general document sharing functionality in the cloud?  I love to have the ability to drag and drop .ods files [for example] to the cloud to share them across platforms.  Does this already exist and I'm