I want to pass a date that is in GTM0 to my local time, according to momentjs it 's like this , but I can't convert the date to my local time.
moment.locale('es');
let fecha = '2018-12-07 22:56:48';
let fecha_origin = moment(fecha).format('DD [de] MMM [del] YYYY [a las] hh:mm:ss A');
console.log('Fecha original: ', fecha_origin);
let fecha_local = moment(fecha).utc().format('DD [de] MMM [del] YYYY [a las] hh:mm:ss A');
console.log('Conversión: ', fecha_local);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
Update 1:
My local time is supposed to be -5, instead it's +5 when I do the conversion.
The problem is that you are trying to parse a date that has no UTC information anywhere. That can be known immediately if we break down the date you use as input
The date would be
2018-12-07
and the time22:56:48
separated by spaceThe UTC information should go at the end as
+hh:mm
or-hh:mm
, if it is in UTC it should be+00:00
Changing the date input works perfectly. I used
T
as a spacer.The other way is that instead of
moment(fecha).utc()
usingmoment.utc(fecha)
it directly since, as you say, it comes in utc from the server.The difference is in how it is processed . Remember that your initial date has no offset information so if you use
moment(fecha).utc()
what it will do is interpret it as local time and then convert it to utc by adding or subtracting hours (hence your problem). If you specify itmoment.utc(fecha)
then it will interpret it as utc directly, that is+00:00
Let's first understand how dates work with moment.js, by looking at examples, but first:
This only affects the language, that is, whether to write Dec(ember) or dic(ember), not the time. Therefore we can rule it out as a cause of problems
You define a moment in a standard format . But what time is it? Let's do some tests to check it out. I am in GMT+1 (Spain):
We already see a difference: without formatting, Zulu time is used (hence the final Z), while when formatting, the Local Zone of my machine's operating system is used.
Zulu time is UTC time , which coincides with GMT+0
Now let's try to parse a date:
So we see that the problem is that when you write:
You are making a misconception:
utc() should go on the original date and on the local date apply local(). With the following example ami it works perfectly for me. The code should look like this:
This way I get the date with the time zone you need: The image shows the capture in the console. (Do the test locally)