Time if statement not working - javascript

Hi I have a simple if statement which compares to dates, however its not running, I have tried debugging it but doesn't work.
dateFormat = "01/05/2099"
dateMissing = "25/11/2016"
if(dateFormat > dateMissing){
dateFormat = dateMissing;
}

You're comparing strings. That compares their characters, one by one from left-to-right, until it finds a difference, and then uses that difference as the result. Since "2" is > "0", that string is greater than the other.
You need to parse the dates and compare the result. Do not just use new Date(dateFormat) or similar, those strings are not in a format that is handled by JavaScript's Date object. Do the parsing yourself (directly, or via a library). E.g.
var dateFormat = "01/05/2099";
var dateMissing = "25/11/2016";
var parts, dt1, dt2;
var parts = dateFormat.split("/");
var dt1 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
parts = dateMissing.split("/");
var dt2 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
if (dt1 > dt2) {
dateFormat = dateMissing;
}
console.log("dateFormat:", dateFormat);
console.log("dt1", dt1.toString());
console.log("dt2", dt2.toString());

Your can't simply compare the strings containing dates. First, convert them to an acceptable format (milliseconds).
var dateFormat = new Date("05/01/2099").getTime();
var dateMissing = new Date("11/25/2016").getTime();
Then you can do your date comparision.

Related

determine if a timestamp in this format is within a particular range in JavaScript

I have a bunch of timestamps that have the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.
I am trying to write a function to determine if a given timestamp is within a range:
function isBetween(start, end, toCompare) {
}
for example, isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59") should return true as "2017:01:01:23:59:59" is between '2017:01:01:23:59:58' and "2017:01:02:23:59:58"
I couldn't find a clean way to do it. Can someone help me with this?
In JavaScript, Date objects can be compared fairly easily. However, as you've probably noticed, the format of the string you provided is not a format that can be parsed by JavaScript's Date object, so we will first have to fix that. Fortunately, this format is extremely predictable.
The first thing I notice is that the "Month" and "Date" are preceded by a zero if they're a single digit. This means that the date portion is always the exact same amount of characters (10). Because this is the case, we can use String.prototype.substring() to get the first 10 characters for the date, and get everything after the 11th character to get the time while skipping the colon in the middle.
var datetime = "2017:01:01:23:59:58";
var date = datetime.substring(0, 10);
var time = datetime.substring(11);
console.log("Date: " + date);
console.log("Time: " + time);
Now that they're separate, all we need to do is replace the colons in the date with forward slashes, then concatenate it with the time separated by a space. After this, we will have a date string in the MM/dd/yyyy hh:mm:ss format, which we can then parse using JavaScript's built in Date class.
var input = "2017:01:01:23:59:58";
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
console.log(new Date(datetime));
Now we can throw this into it's own function, then use simple comparison to figure out if toCompare is between start and end.
function isBetween(start, end, toCompare) {
var startDate = convertDate(start);
var endDate = convertDate(end);
var compareDate = convertDate(toCompare);
return compareDate > startDate &&
compareDate < endDate
}
function convertDate(input){
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
return new Date(datetime);
}
var between = isBetween("2017:01:01:23:59:58", "2017:01:02:23:59:58", "2017:01:01:23:59:59");
console.log(between)
This could work for you:
function isBetween(start, end, toCompare) {
start = dateGenerator(start)
end = dateGenerator(end)
toCompare = dateGenerator(toCompare)
if(start <= toCompare && toCompare <= end) return true
return false
}
function dateGenerator(str) {
str = str.split(":")
let date = new Date(`${str[0]}-${str[1]}-${str[2]}`)
date.setHours(str[3],str[4],str[5])
return date.valueOf()
}
const truthy = isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59")
console.log(truthy)
Firstly get individual values and add accordingly to Date constructor of JS and set the hours accordingly.
For comparison we can convert this unix figures (valueOf), hence it will be easier to compare.
This may seem as complex approach but it works.

How to check if the time is in between given range using moment.js?

I am using moment.js library for time.
I want to check if the time I am getting from the backend is in between 8AM to Noon (12PM). I want to store all the objects whose time is in between 8AM to 12PM.
I am getting date in this format - "2022-04-04T21:43:59Z". I want to use timezone"America/Detroit".
Here is what I have tried but this didn't work;
//this code is inside forEach loop
moment.tz.setDefault($scope.userData.account.timeZone);
var format = 'hh:mm:ss'
var time = moment(response.date,format),
beforeTime = moment('08:00:00', format),
afterTime = moment('11:59:59', format);
if (time.isBetween(beforeTime, afterTime)) {
console.log('is between')
} else {
console.log('is not between')
}
In the output I am getting is not between for all the data but in real there is some data which is having date and time falling under 8am - 12pm.
Is there anything wrong because of timezone?
The reason why your compare isn't working it's because it's not only using time but also the date.
You should first extrapolate the time from the input datetime and use that data to make the comparison like this:
let datetime = moment('2022-04-04T10:00:00Z', 'YYYY-MM-DDTHH:mm:ssZ');
moment({
hour:datetime.hour(),
minute:datetime.minute(),
second:datetime.second()
}).isBetween(beforeTime, afterTime);
//returns bool true or false
That's because all those 3 datetimes will lay in the same solar day and only time will be relevant to the comparison.
Plus you incorrectly dealt with formats when parsing both your input datetimes and times used for before and after.
This is a working solution showing the concept:
//those are the formats your input uses for datetimes and times
const datetime_format = 'YYYY-MM-DDTHH:mm:ssZ';
const time_format = 'HH:mm:ss';
//this is your input crafted as objects having the prop date
var response_timeYESInBetween = {date : "2022-04-04T10:00:00Z"};
var response_timeNOTInBetween = {date : "2022-04-04T21:43:59Z"};
//moment.tz.setDefault($scope.userData.account.timeZone);
//this is where you parse those timestamp strings as moment datetime
var datetime_YESInBetween = moment(response_timeYESInBetween.date, datetime_format);
var datetime_NOTInBetween = moment(response_timeNOTInBetween.date, datetime_format);
//this is where those moment datetime get used to create new datetimes holding those same time but laying on today instead of their original dates
var timeonly_YESinBetween = moment({hour:datetime_YESInBetween.hour(), minute:datetime_YESInBetween.minute(), second:datetime_YESInBetween.second()});
var timeonly_NOTinBetween = moment({hour:datetime_NOTInBetween.hour(), minute:datetime_NOTInBetween.minute(), second:datetime_NOTInBetween.second()});
//this is where we create datetimes (ignoring to pass the date, sets them at today)
var beforeTime = moment('08:00:00', time_format);
var afterTime = moment('11:59:59', time_format);
//we make the comparison to know which times are between beforeTime and afterTime
//note: now all those datetimes are all in the same day and only time will affect the comparison result
var firstComparison = timeonly_YESinBetween.isBetween(beforeTime, afterTime);
var secondComparison = timeonly_NOTinBetween.isBetween(beforeTime, afterTime)
console.log( firstComparison );
//outputs: true
console.log( secondComparison );
//outputs: false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
And if we wanted to better factor the parts:
console.log( isBetween('2022-04-04T10:00:00Z', '08:00:00', '11:59:59') );
//true
console.log( isBetween('2022-04-04T21:43:59Z', '08:00:00', '11:59:59') );
//false
function isBetween(datetime, before, after){
const datetime_format = 'YYYY-MM-DDTHH:mm:ssZ';
const time_format = 'HH:mm:ss';
let originalDatetime = moment(datetime, datetime_format);
let transformed = moment({hour:originalDatetime.hour(), minute:originalDatetime.minute(), second:originalDatetime.second()});
var beforeTime = moment(before, time_format);
var afterTime = moment(after, time_format);
return transformed.isBetween(beforeTime, afterTime);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

Round Date up or down using Moment

I am using Moment to compare two datetime values. Specifically using Moment.isSameOrBefore. My two date values are off by milliseconds.
I would like these two values to evaluate as the same:
var date1 = '2019-07-09T15:30:05.8670088'
var date2 = '2019-07-09T15:30:06.3400766'
if (moment(date1).isSameOrBefore(date2, 'second')) {
//do something
}
Is there a way to round, so the datetime values equal so evaluation is true? Or another way to achieve this?
It evaluates as true:
var date1 = '2019-07-09T15:30:05.8670088'
var date2 = '2019-07-09T15:30:06.3400766'
var test = moment(date1).isSameOrBefore(date2, 'second');
console.log(test);
<script src="//unpkg.com/moment"></script>

Google forms to calendar event issues with date format

So I have a very simple form that takes 3 inputs, a title, start and end date. I have tried to use a simple script to produce a calendar event. this can be seen below.
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(e.values[2]);
var end_time = new Date(e.values[3]);
CalendarApp.createEvent(title, start_time, end_time);
}
The issue I have is that as the date string is UK format (e.g. 05/12/2016 12:00:00) it is logging the events as 12th May as opposed to 5th December.
I am new to all of this so am looking for an elegant and simple solution I understand, not just to copy code I don't.
Thanks.
function convertUKDateToUSDate(date) {
const arr = date.split('/');
const temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
return arr.join('/');
}
will convert a date string with the prefix "DD/MM/" into "MM/DD/YYYY" format. Split turns the string into an array like ["DD", "MM", "YYYY HH:MM:SS"] and then the temporary variable is used to swap the "MM" and "DD" before the array entries are joined back together with the same character that was used to split them. You'll end up with a final onFormSubmit(e) like this:
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(convertUKDateToUSDate(e.values[2]));
var end_time = new Date(convertUKDateToUSDate(e.values[3]));
CalendarApp.createEvent(title, start_time, end_time);
}
Obviously I'm assuming e.values[2] and e.values[3] are strings. If they're Date objects already (or if you just want a shorter solution), then consider using the Moment.js (the premier Date object library) format function to convert between the formats. Normally I'd recommend using Moment anyways but you said you wanted something you could understand instead of copy.

How to format this JSON data to date(mm/dd/yyyy)

Sample JSON:
[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]
I have this set of dates and I want to convert it to the date format (mm/dd/yyyy). How do you do this is JavaScript?
Unfortunately parsing and formatting dates is a weak side of javascript.
So usually for that we use the 3rd party libraries like moment.js
An example of how you would do that with moment.js:
var date = '2014-05-28T01:34:00';
var parsedDate = moment(date);
var formattedDate = parsedDate.format('MM/DD/YYYY');
Demo: http://jsfiddle.net/8gzFW/
You may format the json string into new Date() then use js methods to get month,day,year or what exactly you need.
//format string to datetime
var DispatchDt = new Date(this.DispatchDt);
// then use this methods to fetch date,month, year needed
//getDate() // Returns the date
//getMonth() // Returns the month
//getFullYear() // Returns the year
var DispatchDt_date = DispatchDt.getDate();
var DispatchDt_month = DispatchDt.getMonth() + 1; //Months are zero based
var DispatchDt_year = DispatchDt.getFullYear();
Sample on jsFiddle
This would work
var a = "[{"DispatchDt":"2014-05-28T01:34:00","RcvdDt":"1988-12-26T00:00:00"}]";
var b = JSON.parse(c);
for (i in b[0]) {
b[0][i] = b[0][i].slice(0, 9)
}
console.log(b); // b now looks like this [ { DispatchDt: "2014-05-28", RcvDt: "1988-12-26" } ]
Please note the dates are stringified.

Categories

Resources