Getting wrong date in Node.js - javascript

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);

Related

Error converting selected date - Angular 8

I am making a filter between two dates, Start date and End date, the filter works perfect, it brings the data but it does not bring the complete data and it is because when selecting the dates and converting them to the format, it converts them but one day remains.
This way I am converting the dates:
FiltrarPorFechas(incial, final) {
this.ListaUsuarios = [];
const IniDate = new Date(incial);
const EndDate = new Date(final);
}
associate an image with debug and conversion:
As shown in the image, the initial and final dates arrive at the method thus "2019-07-10" and "2019-07-31" but when I try to convert them it puts them one day less as shown in the image.
I have tried to use moment formatDate and it does not work, I do not understand why and I do not want to add one day.
Somebody could help me ?
You may be potentially having an issue with Timezone. You could reset the time to 00:00:00 either using moment.js or from a normal Date() object.
Now, since your aim is to compare the times, you can use the diff() available from moment.js to achieve this. Please find the sample code below
(function() {
initial = '2019-07-09';
initial_formatted = moment(new Date(`${initial} 00:00:00`));
final = '2019-07-31';
final_formatterd = moment(new Date(`${final} 00:00:00`));
console.log(initial_formatted.diff(final_formatterd, 'days'));
// moment(new Date(`${incial} 00:00:00`)).format('YYYY-MM-DD HH:mm:ss');
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
More info
Moment diff()
Date Object set() method

Moment.js resolve timezone offset

I'm working in an Angular 6 front end and receive from another system time stamps which have no time zones (C# backend, DateTime). I suspect that javascript is automatically adding the local time zone to Date objects.
Example:
Receiving from backend: 2018-10-15T07:53:00.000Z
When console logging: console.log(timestamp) // Mon Oct 15 2018 09:53:00 GMT+0200
I am using moment.js and already tried moment.utc() and moment(DATE).utc(). But it still adds the local time zone especially because I have to re-transform my moment objects back to the type Date with .toDate().
How can I resolve the time zone difference and get back a utc date to work with or the same structure as received?
try to format use as per desired.
let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str)
console.log(moment.format('DD/MM/YYYY HH:mm'))
<script src="https://momentjs.com/downloads/moment.js"></script>
Second Snippet (to use the date object from string)
let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str);
console.log(moment.toDate())
<script src="https://momentjs.com/downloads/moment.js"></script>
Your input is UTC and will be parsed just fine. Javascript Dates have no notion of timezone! The local timezone is applied by the static methods for serializing (Date.toString(), Date.toDateString() etc.) (Console.log(Date) uses Date.toString().)
Use Date.toLocaleString([],{timeZone:"UTC"}). Forcing UTC, you will see in the output the same time as the input. Much more details are here :-)
Here it is working:
console.log(new Date('2018-10-15T07:53:00.000Z').toLocaleString([],{timeZone:'UTC'}))

moment.js returns different timezones

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>

parsing a UTC ISO date to a local time date in javascript/jquery

I have tried to search for the answer already, and although I find answers that are very similar, I don't think they are exactly what I am looking for. Please forgive me if this is already answered elsewhere.
I am trying to parse an ISO date in javascript so that I can compare it to the client system date and display information depending on if the ISO date is before or after the client system date.
This was fine until I needed to support IE8 and now I am stuck.
I have created a function because I have three different dates that I need to do this to.
for example, my ISO date is: 2015-12-22T11:59 in UTC time.
but once my date is parsed, the full date is 11:59 in local time, no matter which time zone i test, it's always 11.59 in THAT time zone.
I know that the function I have created currently doesn't do anything with timezone, this is where I am stuck. I don't know what to add to get my end date to change as a reflection of the timezone of the clients machine.
any help or advice would be greatly appreciated.
I am not able to use something like moments.js because I have an upload restriction.
Jquery is available though. or plain javascript.
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
The simple solution is to append Z to the ISO date to indicate it is in UTC time, such as 2015-12-22T11:59Z.
When JavaScript parses that date as a string, it will then automatically convert the UTC date to the local time zone.
While this is simple enough with a parsing call in the form new Date(str);, it will not play nice with your parse call with numerical arguments targeting IE8 and other old browsers.
A polyfill for parsing ISO dates with timezone exists: Javascript JSON Date parse in IE7/IE8 returns NaN
This can replace your custom parseDate function after some modification to take an input string.
Alternatively, implement your own custom date manipulater to account for the local timezone using the .getTimezoneOffset() method on the newly created date, which gives the time zone offset in minutes, but you will have to come up with a method of utilising the offset such as adjusting hours and minutes, due to the limited methods of the JavaScript date object.

Moment.js Convert Local time to UTC time does work

I would like to use Moment.js to convert a local time to UTC equivalent. I believe that I have the correct method in place, but it does not alter the time.
I'm in Sydney Australian +11 and expect the UTC time to be 11 hours earlier.
Internally on the moment object the isUTC flag changes from false to true, but the time does NOT shift, am I meant to use a different technique for this.
How do I actually get the current UTC date out of this object
Before Conversion
var val = '18/03/2015';
var selectedDate = moment(val, 'DD/MM/YYYY');
After Conversion
var a = selectedDate.utc()
I just tried this code and it seems like I get the correct UTC time. I guess I just want to confirm that what I am doing is correct way to access the UTC time from moment.js
a.format("YYYY-MM-DD HH:mm:ssZ")
I found that my usage pattern of in my application was incorrect
selectedDate.utc().format(fullFormat)
It should have been
moment.utc(selectedDate).format(fullFormat)
This works
moment(date_to_convert).utc().format("YYYY-MM-DD HH:mm:ss");
The question is old, but I also faced it. It may be useful to someone:
Using the method of utcOffset() to calculate the UTC time:
selectedDate = (moment(selectedDate).add(-(moment().utcOffset()), 'm'));
And explicitly specify UTC:
selectedDate = moment.parseZone(selectedDate).utc().format();
This is how you do it using moment-timezone
moment.tz(localDate, localTimeZone).utc()
This worked for me !!
selectedDate = moment(selectedDate).add(moment(selectedDate).utcOffset(), 'm').utc().format()
Create a local moment object from you local time and convert it to UTC then format it, then create a new UTC moment from that formatted UTC string
var localDateString = '24/04/2019';
var localDateStringFormat = 'DD/MM/YYYY';
var utcMoment = moment.utc(moment(localDateString, localDateStringFormat ).utc().format('YYYY-MM-DD HH:mm:ssZ'))
console.log(utcMoment);
<script src="https://momentjs.com/downloads/moment.js"></script>
After few frustrating hours, I found what was the problem
Short Answer: To convert time to utc, we need to use format()
Long Answer: Take the example
moment.utc(1559586600000).format('LLL')
.utc sets the isUTC flag to true.
When logging the date, the d key always shows the time in local timezone. (Which makes us believe its not working properly - as shown in your screenshot)
But we need to use .format to get the date/time in UTC format.
The above code returns June 3, 2019 6:30 PM which is the correct UTC time.
const moment = require('moment-timezone');
const dateTime='2020-12-21'
const timezone='America/Anchorage'
const dateTimeInUtc = moment(dateTime).tz(timezone).utc().format();
console.log('dateTimeInUtc',dateTimeInUtc);
const moment = require('moment-timezone');
const dateTime='2020-12-21'
const timezone='America/Anchorage'
const dateTimeInUtc = moment(dateTime).tz(timezone).utc().format();
console.log('dateTimeInUtc',dateTimeInUtc);
After few frustrating hours, I found what was the problem
Short Answer: To convert time to utc, we need to use format()
Long Answer: Take the example
moment.utc(1559586600000).format('LLL')
.utc sets the isUTC flag to true.
When logging the date, the d key always shows the time in local timezone. (Which makes us believe its not working properly - as shown in your screenshot)
But we need to use .format to get the date/time in UTC format.
The above code returns June 3, 2019 6:30 PM which is the correct UTC time.

Categories