I'm parsing a XML file with Javascript and I would like to convert a date to my local time zone using moment.js but I'm stuck. The basic parsing consists of getting the date:
document.write(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue);
Which generates something like 31/12/2016 23:00. With moment.js it's possible to format the date like this:
var utcDate = moment.utc('31/12/2016 23:00', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write(localDate);
Which writes 01/01/2017 01:00 in my current time zone. But I can't figure out how to use the method above with the parsing. Tried modifying the variable but only getting "Invalid date" as a result.
var utcDate = moment.utc('x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write (localDate);
Does anyone have any tips? Might be other solutions than using moment.js but it seemed like the best and most flexible option.
You've put your XML traversal inside a string. That traversal won't happen if it's not actual javascript. Additionally, moment.js will try to parse that literal string as a date, NOT the value from that traversal.
'x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue'
You need to unquote your traversal to get its value, then feed that to moment.js.
var utcDate = moment.utc(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue, 'DD/MM/YYYY HH:mm');
Related
I've got a Datestring like this one: 20171010T022902.000Z and I need to create Javascript Date from this string. new Date('20171010T022902.000Z') would return Invalid Date.
I saw that it's possible to use moment.js for this purpose but I am not sure how I would specify the according format for my given example. I found this example from another thread:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');
var jsDate = momentDate.toDate();
Question:
How can I create a JavaScript date from a given Datestring in this format: 20171010T022902.000Z (using moment)?
Your input (20171010T022902.000Z) matches known ISO 8601 so you can simply use moment(String) parsing method. In the Supported ISO 8601 strings section of the docs you will find:
20130208T080910.123 # Short date and time up to ms
Then you can use toDate() method
To get a copy of the native Date object that Moment.js wraps
Your code could be like the following
var m = moment('20171010T022902.000Z');
console.log( m.format() );
console.log( m.toDate() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Note that this code does not shows Deprecation Warning (cited in Bergi's comment) because you input is in ISO 8601 known format. See this guide to know more about this warning.
Moreover "By default, moment parses and displays in local time" as stated here so format() will show the local value for your UTC input (20171010T022902.000Z ends with Z). See moment.utc(), utc() and Local vs UTC vs Offset guide to learn more about moment UTC mode.
I think you can do this without moment.js,.
Basically extract the parts you need using regex's capture groups, and then re-arrange into a correct format for new Date to work with.
var dtstr = '20171010T022902.000Z';
var dt = new Date(
dtstr.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\.\d{3}Z)$/,
"$1-$2-$3T$4:$5:$6$7"));
console.log(dt);
console.log(dt.toString());
If you are using moment.js anyway, this should work ->
var dt = moment("20171010T022902.000Z", "YYYYMMDDTHHmmss.SSSSZ");
console.log(dt.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
I am receiving date from back end in 2017-03-02T08:12:22.997000+00:00 this format.
To display this date in specified format I am doing
new Date('2017-03-02T08:12:22.997000+00:00').toLocaleString() that gives 3/2/2017, 1:42:22 PM
There's one functionality which is sorting this formatted output.
Agenda is to sort the output based on 'date' type. But since I am using toLocaleString() method for formatting, sorting is done based on 'string' type.
Is there any solution where I can achieve 3/2/2017, 1:42:22 PM format and type will be a Date object?
Or a date format where I can see date along with time excluding GMT part? (like toUTCString())
Or any method from moment will work?
you can use moment.js which will give you moment object.
first convert date to IsoDate as moment.js latest version has deprecated moment constructor with illegal date string ( more info here )
var isoDate = new Date('2017-03-02T08:12:22.997000+00:00').toISOString(),
formatedDate = moment(isoDate).format('DD/MM/YYYY, HH:MM:SS A');
// formatedDate : "02/03/2017, 13:03:99 PM"
you may use Timezone for better handling of time -
moment(isoDate).tz('timezoneValue').format('DD/MM/YYYY, HH:MM:SS A');
In my php application I set the italian timezone like this way:
date_default_timezone_set('Europe/Rome');
the string above is located in my config.php file, the core of the app. Anyway, from the backend I using momentjs with CodeIgniter framework. When a user select a date from the properly input set this result:
Now I get the value from this input like this:
var end_date_temp = Date.parse($('#end-datetime').val());
And the initial result is wrong:
Tue Mar 01 2016 11:03:00 GMT+0100 (ora solare Europa occidentale)
The rest of code is:
var end_date = moment(end_date_temp).add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);
NB: I also tried to set moment.locale('it') but the same result appear, in my javascript libraries I've the italian timezone of momentjs. What is wrong?
UPDATE Code:
var end_date_temp = moment($('#end-datetime').val())._i;
var end_date = moment(moment(end_date_temp).add(serviceDuration, 'minutes')).format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);
// parse the input string to a moment object, **specifying the input format**
var end_date = moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm');
// manipulate it as desired
end_date.add(serviceDuration, 'minutes');
// format it to the specified output format, and assign the result back to your field
$('#end-datetime').val(end_date.format('DD/MM/YYYY HH:mm'));
You can do this in one line of code if you like.
$('#end-datetime').val(moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm').add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm'));
The locale setting isn't important with this particular bit of code, because you don't use any locale-specific functions or format specifiers
After a lot of attempts, I fixed in my timezone (italian) like so:
moment.locale('it');
var end_date_temp = moment($('#end-datetime').val()).format('DD/MM/YYYY HH:mm')
var end_date = moment(end_date_temp).add(30, 'minutes');
$('#end-datetime').val(moment(moment(end_date).toDate()).format('DD/MM/YYYY HH:mm'));
I declared the .locale as it, in the next time I formatted the time returned from the input text in my timezone as well. I've manipulated the date with the .add method, for do this I've create another instance of momentjs object. At the end I pass the value from the input, re-formatted the date again in my timezone format 'cause in the manipulation I lose the previous formatting. The final result is what I wanted. Hope this help, anyway, if someone find a solution more optimized than my I'll be happy to see.
momentjs is using the american date format (MM/DD/YYYY), enforce a format to get the right date:
var input = '03/01/2016 11:00';
var date = moment(input, 'DD/MM/YYYY HH:mm');
document.write(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>
I have a date time string in format ("2015-10-07 15:20:00 UTC") and i want to convert it to local time zone of client. i am using the following statements for this:
var UTC_Time = new Date ("2015-10-07 15:20:00 UTC");
var localTime = UTC_Time.toString();
in Google Chrome it works fine and return the converted time as 2015-10-07 20:20:00 PST which is fine. But in internet explorer (i am concerned with IE10) it is returning the same UTC date i.e. 2015-10-07 15:20:00. how can i get the converted time in IE. Any help would be greatly appreciated.
When you display a date in javascript, it converts it to the client time. Since you are specifying UTC in your date string, it will assume that it's a UTC date. There are a couple ways you can solve this.
If you just need a string, you can do localTime = UTC_Time.toUTCString().
If you need a js Date object, you can create a new date object by getting the values from the previous object.
new Date(UTC_Time.getUTCFullYear(), UTC_Time.getUTCMonth(),
UTC_Time.getUTCDate(), UTC_Time.getUTCHours(), UTC_Time.getUTCMinutes(),
UTC_Time.getUTCSeconds(), UTC_Time.getUTCMilliseconds());
Or you can simply replace the UTC part of the string.
var dtStr = "2015-10-07 15:20:00 UTC";
dtStr = dtStr.replace(" UTC", "");
var localTime = new Date(dtStr);
Only use this option if you know your string will always be in the same format.
JSON Date: '/Date(1373428800000)/'
End Result: 7/9/2013 8:00 PM EST
Currently I do it in 3 steps:
var a = cleanJsonDate('JsonDate');
var b = formatDate(a); // 7/10/2013 12:00 AM
var c = moment.utc(b); // 7/9/2013 8:00 PM
return c;
Is it possible to accomplish the same result using moment js only?
----Update-----
Combining #ThisClark & #Matt answers. I came as close as possible to the goal; however, the 'h' format does not work for some reason, I still get 20.00.00 instead of 8:00
var m = moment.utc(moment('/Date(1373428800000)/').format('M/D/YYYY h:m A')).toDate();
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>
This format is already supported natively by moment.js. Just pass it directly.
moment('/Date(1373428800000)/')
You can then use any of the moment functions, such as .format() or .toDate()
If you want UTC, then do:
moment.utc('/Date(1373428800000)/')
Again, you can call format or toDate, however be aware that toDate will produce a Date object, which will still have local time behaviors. Unless you absolutely need a Date object, then you should stick with format and other moment functions.
I don't see all your code, but if you can just get the value of milliseconds as 1373428800000 out of that json, then you can pass it to moment directly. I think formatDate is a function you wrote. Does it do something important like manipulate time that you require of moment.js, or could you just use the format function of moment?
var date = 1373428800000;
var m = moment.utc(date);
//var m = moment.utc(date).format('M/D/YYYY H:mm A'); <-- alternative format
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>