Iso date string

10 views
Skip to first unread message

Gareth Murfin

unread,
Apr 11, 2018, 9:55:15 AM4/11/18
to CodenameOne Discussions

The api im using requires a string like this:

2018-01-01T15:19:21+00:00

I can build that easy enough in codenameone, all apart from the last bit, for example +00:00, in UK right now its BST so it should be +01:00, so how would I actually produce this stirng in an automated fashion? And for some which works anywhere in the world ? 

Ive written this method but as you can see that bit is hardcoded so api in uk thinks everythign is an hour off, I could hardcode it but then it will need ot change when its back to normal GMT. Im just using UK as an example, I guess the main guestion is how do you get how many hours a time is after or before GMT?

private String getIsoDateString(Date now)
    {
       
        //timePicker.setDate(now); // weird cn1 wont allow this
        java.util.Calendar cal = java.util.Calendar.getInstance();
        String timezone = cal.getTimeZone().getID();
        cal.setTime(now);
       
       int year = cal.get(java.util.Calendar.YEAR);
       int month =cal.get(java.util.Calendar.MONTH)+1;
       int day = cal.get(java.util.Calendar.DAY_OF_MONTH);
       
       String yearS=year+"";
       String monthS=month+"";
       String dayS=day+"";
       if (monthS.length()==1)
       {
           monthS="0"+monthS;
       }
       if (dayS.length()==1)
       {
           dayS="0"+dayS;
       }
       
       String hoursS = cal.get(java.util.Calendar.HOUR_OF_DAY)+"";
       String minS = cal.get(java.util.Calendar.MINUTE)+"";
       String secS = cal.get(java.util.Calendar.SECOND)+"";
       if (hoursS.length()==1)
       {
           hoursS="0"+hoursS;
       }
       if (minS.length()==1)
       {
           minS="0"+minS;
       }
       if (secS.length()==1)
       {
           secS="0"+secS;
       }
       
       //year month day? or yra day month?
        String dateS = yearS+"-"+monthS+"-"+dayS+"T"+hoursS+":"+minS+":"+secS+"+00:00";
        return dateS;
    } 

Shai Almog

unread,
Apr 12, 2018, 1:31:25 AM4/12/18
to CodenameOne Discussions
DateUtil includes the timezone offset value: https://www.codenameone.com/blog/date-util.html

Might be worth adding standard time stamp generation to that class as it's a pretty common use case.
Reply all
Reply to author
Forward
0 new messages