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>
Related
I tried all the solutions i found here but none work.
Im just trying:
var a = new Date();
console.log(a);
//2020-01-12T05:05:17.320Z
//Time in my timezone: 2020-01-12T02:05:17.320Z
I'm from Brazil, o the timezone is -3:00
I already installed moment.js and tryed:
var moment = require('moment-timezone');
moment().tz("America/Sao_Paulo").format();
var a = new Date();
console.log(a);
but i keep getting whithout my timezone. I also tryed setting the TZ without the moment.js and didn't work.
I cant use some solution that change the way to call the "new Date()" because I have to parse a string to an object that contains Date and I use Prompts module, that get a date from console, that already return a date. I don't know what to do more.
Thanks for any help.
*I'm running on Windows, and the time is right, the configuration is pointing to the right timezone
edit1: more info
The best way that I found was add 'getTimezoneOffset' (minutes) using moment.js
//Will returns the current "wrong" time in formart '2020-09-29T19:47:46.411Z'
//Expect: 2020-09-29T16:47:46.411Z
console.log(new Date())
So if you want see the full date in format ('DD-MM-YYYY HH:mm') of any object
var moment = require('moment')
// specificDay is a Date (type: Object) like '2020-09-22T00:00:00.000Z'
// previously retrieved from the database without information about the time('HH:mm')
// Only with 'YYYY-MM-DD'
moment(specificDay, "YYYY-MM-DD").add(new Date().getTimezoneOffset(),'minute').format('DD-MM-YYYY HH:mm')
You're very close. Moment is a Javascript library that makes formatting time very easy. You are creating your moment object, but you're not outputting it.
I made a very slight change (2nd line) and it works as expected:
var moment = require('moment-timezone');
console.log(moment().tz("America/Sao_Paulo").format());
If you want it formatted nicely, see this page: https://momentjs.com/.
For example:
console.log(moment().tz("America/Sao_Paulo").format('lll'));
// output: Jan 12, 2020 2:45 AM
How does it work?
moment() creates a time object (just like new Date(), but it's moment's special time object). .tz() is calling the timezone function and we give it your time zone as a string "America/Sao_Paulo". .format() then outputs it in a nice custom string. console.log() outputs the whole string to the screen.
Node takes UTC timestamp
https://www.google.com/search?client=firefox-b-d&q=current+utc+time+online
So you can convert to a locale string and after that create a new date. This is a example for mexico city
let mx = (new Date()).toLocaleString('se-SE',{ timeZone: 'America/Mexico_City'}) + "Z";
return new Date(mx);
I need to send a date to a backend service that requires a date in the following format.
I have access to moment also.
I am using an input type of datetime on the front end which sends over a date like this: "2017-05-17T10:00"
I have tried new Date("2017-05-17T10:00"); but this returns Wed May 17 2017 11:00:00 GMT+0100 (BST). I have also tried using some moment methods, but cannot get the correct format.
Does anyone know how I can convert the datetime string - "2017-05-17T11:43" to the following '2017-05-17T10:43:03+0100'?
Try moment.format(). Here is the list for reference https://momentjs.com/docs/#/displaying/format/
var dt = new Date("2017-05-17T10:00");
console.log(dt);
//'2017-05-17T10:43:03+0100'
var z = moment(dt).format("YYYY-MM-DDTHH:mm:ssZZ");
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Your date is in ISO 8601 format. If you have access to Moment.js (as you said) you can use format() method as below:
var date = moment("2017-05-17T10:00").format("YYYY-MM-DDTHH:mmZZ");
console.log(date);
// prints "2017-05-17T10:00-0300"
Try it.
I'm using this code to create 2 dates that represent a filter date range (in this case the last 3 months):
$ctrl.startDate = moment().utc().startOf('month').add(-2, 'months').toDate();
$ctrl.endDate = moment().utc().endOf('month').add(0, 'months').toDate();
However the first returned date is timezone CET (GMT+1) (which is my zone) and the second is CEST (GMT+2). I have no idea why! I have tried using utc() to get "neutral" dates without success.
Returned dates:
01.01.2017 01:00:00 CET
01.04.2017 01:59:59 CEST
I want either GMT or CET but the same zone! Where does moment take these 2 zones from?
I've come so far that I think it is a bug.
I use version 2.17.1
Any ideas?
JSFIDDLE:
https://jsfiddle.net/FLhpq/8807/
I don't know if you can consider it a bug, in your fiddle you are showing in the result of toDate() that as docs says:
get the native Date object that Moment.js wraps
If you look at momentjs the code you will see that toDate() implementation:
function toDate () {
return new Date(this.valueOf());
}
simply uses new Date() that returns a JavaScript date object in local time, see MDN Date:
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.
If you use format() in your code you will always see +00:00 offset.
var divUtc = $('#divUTC');
var divLocal = $('#divLocal');
var startDate = moment.utc().startOf('month').add(-2, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
var endDate = moment.utc().endOf('month').add(0, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
//put UTC time into divUTC
divUtc.text(startDate);
divLocal.text(endDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>
UTC<br/>
<div id="divUTC"></div><br/>
Your Local Time with respect to above UTC time<br/>
<div id="divLocal">
</div>
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');
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>