JavaScript Date() differs when timezone changes - javascript

I need to convert my date to mm-dd-yyyy format. So I used a method like this:
var dt=new Date(2016-06-21);
var ddte='';
ddte=(("0" + (dt.getMonth() + 1)).slice(-2))+"-"+(("0" + dt.getDate()).slice(-2))+"-"+dt.getFullYear();
It works fine in my local timezone (GMT+05:30). But when I change my timezone to GMT -5:00, it gives the wrong result: 06-20-2016. The result I want is 06-21-2016.
Can anyone please explain the problem?
How can I get the correct result?
Is it a bug?

Your date passed to Date() constructor will be treated as UTC time zone. Getting the time with Date.getMonth() will get your local time zone. You're probably looking for Date.getUTCMonth().
var dt=new Date("2016-06-21");
var ddte='';
ddte=(("0" + (dt.getUTCMonth() + 1)).slice(-2))+"-"+(("0" + dt.getUTCDate()).slice(-2))+"-"+dt.getUTCFullYear();
console.log(ddte);
Though in this case I see no use for using Date at all; this should suffice:
var parsedDate = "2016-06-21".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2-$3-$1");
console.log(parsedDate);

It isn't a bug. It's just how time zones work (it isn't the same calendar day everywhere in the world at the same time).
If you don't actually want advanced date features (it seems you only want some good old string manipulation) my tip is to just not use Date in the first place.
var parts = "2016-06-21".split("-");
var mdy = parts[1] + "-" + parts[2] + "-" + parts[0];
Add some error checking and you're done.

Related

Why am I getting weired date in javascript?

I am using javascript date and I am trying to get it in my own format(YYYY-MM-DD). However, I could manage the format but the problem here is I am getting a day ahead. For eg: if the day is 3(today), here with this code I am getting 4.
let currentDate = new Date(currentForm['dobs']);
let middleDate = currentDate.toLocaleDateString().split('-');
let finalDate = middleDate[0] + '-' + middleDate[1] + '-' + (middleDate[2] - 1);
console.log(finalDate);
Here, in currentDate I am getting date as: 2051-06-30T18:15:00.000Z
But, in finalDate, I am getting 2049-6-31
Ignoring the syntax, why am I getting a day ahead ? How to achieve a correct date ??
I used to have this question few years ago and the reason is really simple. It's because of the 'Z' character at the end of the date value, because for the .toLocaleDateString() function(given that you haven't specified parameters, here is more info) implies this value lies in the UTC+0 zone and for some kind of reason that is always throwing you one day a head.
Solution:
To solve this you have many options, but maybe the simplest one is to format the date by yourself like this:
function lz(n){return n<10 ? '0'+n : n}
var d = new Date('2019-01-01T00:00:00Z');
var formatted = d.getUTCFullYear()+'-'
+ lz(d.getUTCMonth()+1)+'-'
+ lz(d.getUTCDate())+' '
+ lz(d.getUTCHours())+':'
+ lz(d.getUTCMinutes())+':'
+ lz(d.getUTCSeconds());
Or you can use third-party libraries like moment.js which, by the way, is pretty popular. Here is a link for more info.
Edit:
My apologies I was omitting one part of my code since I took it directly from one of my projects. Please follow the above code or test it in this fiddle.
As per #Alfredo Zamudio answer, I tried to remove that 'Z' attached at the end of my date value and after that everything ok.
let currentDate = new Date(currentForm['dobs']);
let newDate = currentDate.toISOString().replace('Z', '');
After these lines of code my issue was solved and then I used simple technique to format date.
let formattedDate = newDate.getFullYear() + '-' + newDate.getMonth() + '-' + newDate.getDate();
Thanks to all !

How to compare two dates in moment JS

I have two inputs, one is a date, the second is a time. I need to check if that date and time is in the past or not.
I'm currently residing in Toronto,
My Date input is 8/15/2019
My Time input is 12:00
The issue I face is that when I grab the current date (right now it's 11:00 am. 8/15/2019) the time I actually get is 19:00 which makes the entire comparison incorrect.
What I tried
var startDateString = moment("8/15/2019" + " " + 12:00, "MM/DD"YYYY" + " HH:mm", true).format();
produces
`2019-08-15T12:00:00+04:00`
but current date in a string format is quite different.
var now = moment().format();
produces
`2019-08-15T19:00:00+04:00`
I was thinking it should have created a value of 2019-08-15T11:00:00+04:00
If I can get some tips or assistance on how to correct compare dates, would be greatly appreciated. Maybe I have to offset current moment()?
You could offset the time yourself, but that's unnecessary since you're already using Moment. Moment has an add-on library called Moment Timezone, which allows you to set the timezone for a date and convert between different time zones almost effortlessly.
Try including Moment Timezone (and the associated 10-year data) in your environment, then calling:
var startDateString = moment.tz("8/15/2019" + " " + "12:00", "MM/DD/YYYY" + " HH:mm", "America/New_York").format();
You can also operate on the time to convert it between different time zones like so:
let startDate = moment.tz("8/15/2019" + " " + "12:00", "MM/DD/YYYY" + " HH:mm", "America/New_York");
let la_startDate = startDate.clone().tz("America/Los_Angeles");
let la_startDateString = la_startDate.format();

How to parse string to date with hour in JavaScript?

I've got string with date
var day = '2016-04-20'
And i want to parse it to 2016-02-01 23:59:59 because when i'll send this string as a query to database. Then is recognize as 2016-04-20 00:00:00.
I know that i could sent it like this: day+' 23:59:59' however it looks unprofessional ;)
#EDIT
I think good idea would be: Date.parse(day) + 1 however Date.parse return the number of milliseconds between January 1, 1970 and the day.
you can do it in mysql date format like this
SELECT DATE_FORMAT(date,'%y:%m:%d %T:%f')
e.g date is '2016-04-20'
then
SELECT DATE_FORMAT('2016-04-20','%y:%m:%d %T:%f')
This...
var day = '2016-04-20'
var mydate = new Date(day);
mydate.setMinutes(mydate.getMinutes() - 1);
var mydatestring = mydate.toISOString().slice(0, 10) + " " + mydate.toISOString().slice(11,19);
...however be VERY careful as JS on the clients machine can very often be different to the server time, even in the same country! so don't expect the times to be 100% correct
UPDATED - first version missed the point of the question

JavaScript time is an hour behind after ISO conversion

I create a new Date in JavaScript, with the correct time, but after I use toISOString() to convert it, it's an hour behind. Why would that be?
https://jsfiddle.net/73nfyxeL/
var createdDateTime = new Date('2015-04-01 11:53:00');
var isoCreatedDateTime = "";
alert(createdDateTime);
isoCreatedDateTime = createdDateTime.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/);
alert(isoCreatedDateTime[1] + ' ' + isoCreatedDateTime[2]);
createdDateTime.setMinutes(createdDateTime.getMinutes() + 1);
As far as I'm aware this should be immune to changes to the local time (eg. daylight savings), as I'm giving it a pre-set time, and not a timezone. What's going on?
The toISOString method doesn't only format the date, first it is converted to UTC.
The difference between your local time zone and UTC is one hour.

how to get date and time together in javaScript

Is there a way to get date and time in JS?
I searched in google and saw ways to get the date appart and time appart but not together.
I have a field that calls "Date Time" and i need to show data -12 hours so i need to figure out how to save datetime.
Can someone help?
Use javaScript Date object to work with date and time.
alert(new Date());
Use new Date();
var x = new Date();
You can also fetch each value using .getDay() , .getMonth(), .getYear(), .getHours(), .getMinutes(), .getSeconds()
Like
x.getHours(); // Will give you hours.
use date object of javascript then adjust your date and time combinations
for example, create a function getdateTime which will return dateTime combinations
function getdateTime() {
var date = new Date();
var dataVal=date.getDate() +"/"+ (date.getMonth() + 1)+"/" + date.getFullYear() + ":" + date.getHours() + ":" + date.getMinutes();
return dataVal;
}
var datetime=getdateTime();
console.log("datetime:" +datetime);
output for example : datetime:18/2/2015:14:26
ie current date and time
since months starts from 0 to 11 you have to add 1 to get current month.
you can use other date functions depending upon your requirements.

Categories