How to compare two dates in moment JS - javascript

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

Related

JavaScript Date() differs when timezone changes

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.

moment-timezone parsing the given time zone

I have an issue when parsing the Date object using the moment-timezone
The problem
I am creating a nodejs app that should check the new Date() object with arbitrary time from database (and act accordingly). The time, and the timezone are persisted in database.
In example
time | timezone
11:00| US/Eastern
When a REST call comes, I have to take new Date() object and to transform it to given timezone and see whether the current time is later than 9am. But servers timezone and persisted timezone are not the same.
The issue
I create todays date string like this
function getTodaysDate() {
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
return yyyy +'-' + mm + '-' + dd;
}
And trying to create Timestamp object with moment-timezone
startTime = moment.tz(new Date(getTodaysDate() + ' ' + '11:00'), 'US/Eastern');
But the framework correctly takes the date and transforms it to US/Eastern time zone.
So when I print startTime.format();
I get
2016-08-01T07:00:00-04:00
And I would like
2016-08-01T11:00:00-04:00
So is there a way using moment-timezone package to set the Date and time and to just treat them as given timezone?
So the problem was that
startTime = moment.tz('here the date goes', 'US/Eastern');
Was either expecting ISO format or manually formatted (syntax of this was not known to me), or the Date() object. I first tried with this
2016-08-01 11:00
Moment library complained (I will post the full error message when I come to office).
Solution
Add T.
startTime = moment.tz('2016-08-01T11:00', 'US/Eastern');
I hate timedate libraries and how we track of time.
You don't need any of the Date object manipulation. In theory, you should just be able to do:
var zone = 'US/Eastern'
var time = '11:00'
var result = moment.tz(time, 'HH:mm', zone).format();
However, there's a known bug with this that uses the UTC current date instead of the time zone's current date. Until it's fixed, you have to do this instead:
var zone = 'US/Eastern'
var time = '11:00'
var s = moment.tz(zone).format('YYYY-MM-DD') + ' ' + time;
var m = moment.tz(s, zone);
var result = m.format();
(this assumes your input time value is in HH:mm format)

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.

getTimezoneOffset() method return different time on localhost and on server

I have a function in which I am calculating the current user location time based on the Australian NSW timezone minus the local offset. So for example I want to compare an event starting time in Australian (NSW) local time vs my local time I am getting the correct value if I open the website on my localhost. However I am getting 1 hour different if I visit the website on the uploaded server (test environment). So if the correct time is 04:00 on localhost I am getting 05:00 on the test environment.
Here is my function:
var date = {
formatFullDate: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
month = this.addZeroToFront(localDate.getMonth() + 1),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return localDate.getDate() + '/' + month + '/' + localDate.getFullYear() + ' ' + hour + ':' + minute;
},
formatTime: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return hour + ':' + minute;
},
addZeroToFront: function(whatever) {
if (whatever < 10) whatever = "0" + whatever;
return whatever;
},
getUTCtimeOffset: function() {
var date = new Date();
return date.getTimezoneOffset();
},
getLocalTimeFromAustraliaTime: function (date, gmtTimeOffset) {
var gmtTime = new Date(date.getTime() - gmtTimeOffset*1000),
localOffset = new Date().getTimezoneOffset(),
localDate = new Date(gmtTime - localOffset*60*1000);
return localDate;
}
}
Some general details for my specific case:
Aus/NSQ time zone: UTC/GMT +10 hours
Finnish timezone: UTC/GMT +3 hours
So there is 7 hours different between AUS/NSW and Finland and the result is correctly displayed on localhost but not on the test environment. I am not sure why there is 1 hour different between these 2 cases.
EDIT: 1
This is how I am displaying the current local time
var tr = $('<tr style="cursor:pointer; color: #000000" id="' + categoryId + '_' + raceNumber + '_nextRaceTr"/>')
.append($('<td/>')
.append($('<p/>')
.html(date.formatTime(new Date(value.time), value.timezoneOffset))))
Where as time and timezoneOffset are the JSON response.
P.S - Dont pay attention if I am missing enclosing brackets or any other syntax error. I have only copied a small piece of code just to show how I am displaying the time on HTML.
The JavaScript Date object is always influenced by the time zone settings of the environment where it is running. In most cases, that's the user's browser. Users of different time zones will get different results running your code.
In general, you should beware of any code that follows a pattern like this:
var adjustedDate = new Date(someOtherDate.getTime() - someOffset);
You might think you're cleverly adjusting the behavior of the Date object to a different time zone, but in reality you're changing the referenced point in time and leaving the time zone the same!
Also, consider where you have:
var localOffset = new Date().getTimezoneOffset();
You might think you're getting the time zone offset for the user, but actually you are just getting the current time zone offset for the user. Remember, new Date() initializes to the current moment in time. The moment you're working with might have a completely different offset, depending on if the user happens to be in a time zone with daylight saving time or not and whether it was in effect at that time.
As far as your code goes, it's a bit difficult to tell what you're after since you didn't give examples of your input. You might want to take a look at moment.js, which has most of the formatting functions you might be looking for.
BTW - I don't see anything in your code that would actually bind it to any of the Australian time zones.
I recommend that you convert all times to UTC and store in that format. When you display a time for a user, you can convert to their local time from UTC. Just make sure that you do all calculations/conversions on the same machine on which you are going to display the time (e.g. if you are displaying dates in a webpage, don't calculate the local time on the server, send down an epoch timestamp to the browser and then convert it to local time using JavaScript).
var d = new Date(1413409549000);
alert(d.toString());

Categories