Create Moment from UTC string?

Former Member
Former Member

Hello,

I was wondering if it is possible to create a moment from a UTC string like this "2019-09-27T08:00:00+02:00". It contains useful information ass the UTC offset and that stuff and seems to be standard.

In this case I'm lucky because I can change the format my web-server returns the information, but I may not be so lucky in the future. Is there any way to use that? Is there any lib or barrel?

Thanks in advance

  • You would need to write the code to parse this yourself.

    When working with a time, many webservices return a time stamp in "unix time" which is the number of seconds since Jan1 1970 00:00 UTC.

    It's easy to deal with and can be easily converted into a moment (and possibly a string).  Like this:

    			if(ob["epoch"]!=null) {
    				var ts=ob["epoch"].toNumber();
    				wtime=Helper.timeStr(ts);					
    			}

    With Timestr being:

        function timeStr(ts) {
    		ts=new Time.Moment(ts);
    		var ts2=Calendar.info(ts, Time.FORMAT_MEDIUM);
    		var hour=ts2.hour;
    		var ampm="";
    		if(!Sys.getDeviceSettings().is24Hour) {
    			if(hour>11) {ampm="p";} else {ampm="a";}
    			hour=hour%12;
    			if(hour==0) {hour=12;}
    		}
    		return hour.format("%d")+":"+ts2.min.format("%02d")+ampm;
    	}

    With a result being a string with the local time, in 12/24 hr format as set on the watch.

  • Former Member
    Former Member over 5 years ago

    Anyone found anything easier for this?

    I ended up writing something like the below where I basically used snippets of the UTC string as inputs to create a moment. I also adjusted for time zone manually as I did not found any documentation around creating moments with timezone adjustment parameters. Cheers.

    var options = {
        :year => timeStamp.substring(0, 4).toNumber(),
        :month => timeStamp.substring(5, 7).toNumber(),
        :day => timeStamp.substring(8, 10).toNumber(),
        :hour => timeStamp.substring(11, 13).toNumber(),
        :minute => timeStamp.substring(14, 16).toNumber(),
        :second => timeStamp.substring(17, 19).toNumber()
    };
    var adjustGMT8 = new Time.Duration(28800);
    var timeMoment = Gregorian.moment(options).subtract(adjustGMT8);

  • This is probably pretty close to what you need to do. In an ideal world, you'd parse the time zone offset (instead of hard-coding it as you've done above). Another potential issue is that there are many different formats for ISO8601 date-time strings, and it is a pain in the neck if you want to handle all of them.

    I'll try to throw some code together tonight. Maybe it will be helpful.