Compare timestamps - javascript

Would this code work if both the timestamps are in mysql 2013-03-21 18:16:50 format?
$.get('current.php', { lastTime: time, current: true, Cla: Class }, function(html) {
var Date1 = Date.parse($(html).find("#timestamp").val());
var Date2 = Date.parse($("#timestamp").val());
if (Date.parse(Date1) < Date.parse(Date2)) {$(html).find("#timestamp").remove();}else {$("#timestamp").remove();}
}

I think you want something like this:
$.get('current.php', { lastTime: time, current: true, Cla: Class }, function(html) {
var $dateInput1 = $(html).find('#timestamp'),
$dateInput2 = $("#timestamp");
if ($dateInput1.val() < $dateInput1.val()) {
$dateInput1.remove();
} else {
$dateInput2.remove();
}
// ... add $html somewhere to the DOM ...
});
Since your dates are already in a format that is comparable lexically, it doesn't require using Date.parse() at all. Also, you'd only be creating one jQuery object per element, so it's more efficient in that way, too.

Date.parse return time in milliseconds which you can use it for comparison.
if (Date1 < Date2) {
$(html).find("#timestamp").remove();
}else {
$("#timestamp").remove();
}

You are calling Date.parse twice on the values, and Date.parse does not accept the milliseconds number returned by the previous invocation as a valid date.
if (Date1 < Date2)
is enough to compare them. Notice that if either of them could not be parsed, you will be comparing to NaN.

Related

Check if date overlaps inside array JS

I have an array which contains a set of start/end date objects (time included)
i.e.
results["records"] =
[0] -[startDate,endDate]
[1] -[startDate, endDate]
I also have another two date objects stored locally as JS variables.
How do I check if these variables i.e. startDateObj && endDateObj OVERLAP with ANY record in the array, by that I mean crossover with any time between and including any start date or end date.
Thank you in advance
Initial attempt below
$(results['records']).each(function() {
console.log('end:' + this[1])
console.log('start:' + this[0])
if(startDateObj < this[1].end && endDateObj > this[0].start) {
alert('this overlaps')
}
});
EDIT: Answer added below
Have a great day!
I'm assuming this structure in your "dateArray" because to check overlaps you need to define a range of date and time.
dateArray: [{start: Date, end: Date}];
dateArray.forEach(date => {
if(startDateObj < date.end && endDateObj > date.start) {
//this is an overlap
}
});
The answer was the full date objects in the array where being treated as a string
so to convert and fix
function toDateString(date)
{
var formatedDate = new Date(date);
return formatedDate;
}
$(results['records']).each(function() {
if(startDateObj < toDateString(this[1]) && endDateObj > toDateString(this[0]))
{
//overlaps
}

Javascript Cannot use .now() on date string

So I wanted to compare two dates inside a post object. I tried to compare the date objects, but that returned NaN. Then I tried converting it to milliseconds since 1970 by using .now() on these dates, but it returned the following error:
It happens: TypeError: a.date.now is not a function
I tried typeof a.date and this returned string. I don't know why I can't use the .now() method. Can someone help me?
the whole function inside of angular service
getPosts(section) {
return this.http.get(url + '/forum/getPosts/' + section )
.map( (posts: any) => {
// posts should be ordened based on latest replies. If there are no replies yet, we compare it to the date
// of the original post
posts.obj.sort((a, b) => {
const aHasReplies = a.replies.length !== 0;
const bHasReplies = b.replies.length !== 0;
if (aHasReplies && bHasReplies ) {
return a.replies.slice(-1, 1)[0].date - b.replies.slice(-1, 1)[0].date;
} else if ( aHasReplies && !bHasReplies) {
return a.replies.slice(-1, 1)[0].date - b.date;
} else if ( !aHasReplies && bHasReplies) {
return a.date - b.replies.slice(-1, 1)[0].date;
} else {
console.log(a.date.now());
return a.date - b.date;
}
});
return posts;
});
}
It should be object, not string, if that's what you meant, because there is no "date string".
Other than that try:
new Date(a.date).getTime()
Because .now is a static method, you always use it as Date.now()
This means, that Date.now() always returns milliseconds elapsed since the UNIX epoch.
For converting to unix time use getTime.
If you want to compare them, compare two dates without conversion.
But keep in mind, that unix time is in seconds, and javascript method return in milliseconds. If you need exactly unix time, divide by 1000.
You can compare two dates in the year-month-day format (yyyy-mm-dd) using regular javascript comparators such as < and > etc
I suggest use moment.js library (https://momentjs.com/docs/) to parse Date from String.
So you can have some thing like
let date = moment(a.date)

Determine if current time is within an array of time ranges

For a website blocking/productivity app written in javascript, I'd like to have a user input a series of time ranges available for free time (in his local time). Example:
06:00-06:30
12:30-13:00
23:45-00:15
24 format is not required (I'm just assuming it will be easier)
The program should then check the specified free time ranges against the current time to determine whether block mode is on or off.
My rough idea is to use an inbuilt Javascript function to grab the current DateTime, and convert it to 24 hour format if necessary. I think the time ranges will be in an array. I'm not sure how to check if the current date is within a range in the array.
The logic must also be able to handle the crossover from 23:00 to 0:00.
Anyways that is my line of thought. Thanks for any suggestions including ones that take a different path.
Anyways that is my line of thought. Thanks for any suggestions including ones that take a different path.
If you want to check if current time is in range then the range should be DATE + TIME as current time is DATE + TIME
Possible solution
You can convert all three datetimes to moment instances and just use
start.isBefore(current)
&& current.isBefore(end)
Moment docs on isBefore and isAfter : https://momentjs.com/
"I'm not sure how to check if the current date is within a range in the array."
You'd loop through the array and compare. I'd suggest storing the ranges as an array of objects where each individual range is something like {start: "10:15", end: "10:45"}.
JavaScript doesn't have time objects, only Date that includes date and time information. So I think it would be easiest to convert the current time to the "hh:mm" format as a string and then just do simple string compares against your range values, rather than worrying about converting the range values to date objects. So:
var timeRanges = [
{ start: "06:00", stop: "06:30" },
{ start: "12:30", stop: "13:00" },
{ start: "23:45", stop: "00:15" }
]
function isTimeInRange(time) {
for (var i = 0; i < timeRanges.length; i++) {
var range = timeRanges[i]
if ((time > range.start && time < range.stop)
|| (range.start > range.stop && (time > range.start || time < range.stop))) {
return true
}
}
return false
}
But you can make the code neater, and shorter, using the array .some() method, with or without arrow functions:
var timeRanges = [
{ start: "06:00", stop: "06:30" },
{ start: "12:30", stop: "13:00" },
{ start: "23:45", stop: "00:15" }
]
function isTimeInRange(time) {
return timeRanges.some(range =>
(time > range.start && time < range.stop)
|| (range.start > range.stop && (time > range.start || time < range.stop))
)
}
function pad(d) {
return ("0" + d).slice(-2)
}
function getCurrentTime() {
var now = new Date()
return pad(now.getHours()) + ":" + pad(now.getMinutes())
}
console.log("Current time in range? " + isTimeInRange(getCurrentTime()))
// test some other times
console.log(isTimeInRange("06:15")) // true
console.log(isTimeInRange("12:35")) // true
console.log(isTimeInRange("13:30")) // false
console.log(isTimeInRange("23:50")) // true
console.log(isTimeInRange("00:14")) // true
Obviously you can change < and > to <= and >= if desired.
Try it
start = "10:10";
end = "16:30";
function isInRange(start, end, current){
start = convertTimeToMinute(start);
end = convertTimeToMinute(end);
current = convertTimeToMinute(current);
return start <= current && current <= end;
}
function convertTimeToMinute(time){
return +time.slice(0,1)*60 + +time.slice(3,4);
}
console.log(isInRange(start,end, "15:20"));
console.log(isInRange(start,end, "20:20"));

Javascript - Convert ####-##-## to Epoch time

Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.
EDIT
Code to date:
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
console.log($("#hv-start-date").val()); // => 2012-08-20
hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
hvEndDate = "end"
}
else {
hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}
var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN
Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.
new Date($('.user-value').val()).getTime(); // => epoch time
new Date('2012-08-12').getTime(); // 1344729600000
Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).
EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime():
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
hvStartDate = new Date($("#hv-start-date").val()).getTime();
}
Simply use the getTime() function. It returns the number of milliseconds since Epoch :
var msSinceEpoch = myDate.getTime();
Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
EDIT : if you have to parse it too, you may :
use new Date(theString) if it has the good format
set yourself the different date fields (see reference) after having parsed it
use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.

Compare dates javascript

I need to validate different date's with some javascript(jquery).
I have a textbox with, the inputmask from jquery (http://plugins.jquery.com/plugin-tags/inputmask). The mask that i use is "d/m/y".
Now i have set up a CustomValidator function to validate the date.
I need 2 functions. One to check if the given date is greater then 18 years ago. You must be older then 18 year.
One function to check if the date is not in the future. It can only in the past.
The function are like
function OlderThen18(source, args) {
}
function DateInThePast(source, args) {
}
As you know the value you get back with args.Value is 27/12/1987 .
But how can i check this date in the functions? So that i can set args.IsValid to True or False.
I tried to parse the string(27/12/1987) that i get back from the masked textbox to a date but i get always a value back like 27/12/1988.
So how could I check the given dates with the other dates?
The simple way is to add 18 years to the supplied date and see if the result is today or earlier, e.g.:
// Input date as d/m/y or date object
// Return true/false if d is 18 years or more ago
function isOver18(d) {
var t;
var now = new Date();
// Set hours, mins, secs to zero
now.setHours(0,0,0);
// Deal with string input
if (typeof d == 'string') {
t = d.split('/');
d = new Date(t[2] + '/' + t[1] + '/' + t[0]);
}
// Add 18 years to date, check if on or before today
if (d.setYear && d.getFullYear) {
d.setYear(d.getFullYear() + 18);
}
return d <= now;
}
// For 27/4/2011
isOver18('27/4/2011'); // true
isOver18('26/4/2011'); // true
isOver18('28/4/2011'); // false
try this to start:
var d = new Date(myDate);
var now = new Date();
if ((now.getFullYear() - d.getFullYear()) < 18) {
//do stuff
}
The javascript date object is quite flexible and can handle many date strings.
You can compare two Date objects or use the Date interface methods, such as getSeconds() of getFullYear() in order to deduce useful data regarding the date.
See Date object reference formore details.
You'll need to construct, modify and compare Date objects - something like this:
// str should already be in dd/mm/yyyy format
function parseDate(str) {
var a = str.split('/');
return new Date(parseInt(a[2], 10), // year
parseInt(a[1], 10) - 1, // month, should be 0-11
parseInt(a[0], 10)); // day
}
// returns a date object for today (at midnight)
function today() {
var date = new Date();
date.setHours(0, 0, 0);
return date;
}
function DateInThePast(str) {
// date objects can be compared like numbers
// for equality (==) you'll need to compare the value of date.getTime()
return parseDate(str) < today();
}
function OlderThan18(str) {
// left as an exercise for the reader :-)
}

Categories

Resources