how to compare date with timestamp - javascript

I have a date in format yyyy-mm-dd(this date type is "Date"). assume this date as userdate. I have two more dates in format yyyy-mm-dd hh:mm:ss+00(date1 and date2) which is of the type Timestamp. assume these two dates as date1 and date2.
for example: 2022-05-02 18:12:44+00.
my requirement is if the userdate lies between date1 and date2 I should list some products from the warehouse. for this, I need to compare the userdate with date1 and date2.
the logic goes like this ..if userdate is in Between date1 and date2 then loop using FTL(freemarker template) for listing products.
the code is mentioned below.
<input type="date" id="myDate">
Submit
when user clicks on "submit" after selecting date. I'm passing this user selected date from url to other page.now I want to compare this userdate with other two dates which are timestamps.and I'm fetching these two timestamps from database table.
how shall I acheive this when the type of dates are different.

You can simply transfer Date to timestamp by getTime method.
let timestamp = date.getTime();
or transfer timestamp to Date by new Date.
let data = new Date(timestamp)

You can directly pass the timestamp into a new date object and then compare the values
const date1 = new Date(timestamp1);
const date2 = new Date(timestamp2);
const userDate = new Date(valueReceivedFromInput);
if(date1<=userDate && userDate<=date2){
// list products from the warehouse
}
Note:
If you are only looking to compare <= and >= then you don't need to use .getTime() unless you are looking to compare dates to check if they are equal like date1.getTime()===date2.geTime().

var date1 = new Date('December 25, 2017 01:30:00');
var date2 = new Date('June 18, 2016 02:30:00');
if(date1.getTime() === date2.getTime()){
//same date
}`enter code here`
best to use .getTime() to compare dates in js

Related

How to prevent changes on timestamp when convert from string to ISODate Javascript?

I have a date in (yyyy-mm-dd) format, i want to get start and end date with timestamps and ISO format, i can concat date and timestamp but i want it in date type not in string,
let date = "2020-09-11";
Expected result should be,
startDate = 2020-09-11T00:00:00.000Z
endDate = 2020-09-11T23:59:59.000Z
The start date is correct, The end date is not correct, it gives different time stamp, 18:29:59.000Z when i set it to setHours(23,59,59),
let startDate = new Date(date);
console.log(startDate);
// output: 2020-09-11T00:00:00.000Z
let endDate = new Date(new Date(date).setHours(23,59,59));
console.log(endDate);
// output: 2020-09-11T18:29:59.000Z
I looked at this question convert string to ISO date time in nodejs, but this does not help me, i don't want to use moment,
Am i doing wrong to convert dates? i am using nodejs.
You should use setUTCHours()
The setUTCHours() method sets the hour for a specified date according to universal time
let date = new Date()
let startDate = new Date(new Date(date).setUTCHours(0,0,0));
let endDate = new Date(new Date(date).setUTCHours(23,59,59));
console.log(startDate);
console.log(endDate);
You could just add the postfix without conversion to a local date.
let date = "2020-09-11",
startDate = date + 'T00:00:00.000Z',
endDate = date + 'T23:59:59.000Z';
console.log(startDate);
console.log(endDate);

Get the date between 2 dates using node.js

In node.js I need to get the date within the date range of particular gap.
Consider two dates:
startDate:2016-07-10T00:00:00.000Z,
payByDate:"13"(13th of every month);
endDate:2016-10-08T00:00:00.000Z
I need an array of dates of monthly or weekly gap between these 2 dates.
My result Should be:(Monthly gap)
[2016-07-13T00:00:00.000Z,
2016-08-13T00:00:00.000Z,
2016-09-13T00:00:00.000Z]
EDIT:
My startdate is 2016-07-10T00:00:00.000Z , so i can calculate the noOfmonths using endDate-startdate, but the array entry should be by payByDate.
I am using MOMENT.JS, but its returning only noOfMonths not the dates. Please share your ideas. Thanks in advance.
Now is it possible to calculate the calculate the Above array.Please note that "payByDate" is string.
you can use getMonth() function to get the month of your date. then keep adding one to it till you reach the end date.
var arrayDates = [];
arrayDates.push(startDate);
var tempDate = new Date(new Date(startDate).setMonth(startDate.getMonth()+1));
while(tempDate < endDate)
{
arrayDates.push(tempDate);
var tempDate = new Date(new Date(tempDate).setMonth(tempDate.getMonth()+1));
}
Abouve logic will work for monthly gap. to get array of weekly gap, use getDate() function and keep adding 7 to it till you reach the end Date
Try using the manipulate method in moment.js to add a month to the starting date until you reach the second date.
Consider this code. Assuming that the first date and the last date are already moments when they are passed into this function, you can use the diff and manipulate methods to create an array of dates by month in between the two different dates:
EDIT:
function monthsBetween(payByDate, startDate, lastDate) {
var months = [];
//finds nearest date to the start date that is on the payByDate
var currentDate = startDate.date(parseInt(payByDate));
//checks if the date is after the startDate and adds a month if it is
if(!currentDate.isSameOrAfter(startDate)){
currentDate = currentDate.add(1, 'months');
}
while (currentDate.isSameOrBefore(lastDate)) {
months.push(currentDate);
currentDate = currentDate.add(1, 'months');
}
return months;
}

Javascript Date Comparison not behaving as expected

I am getting a SQL date - NOT datetime - object pushed into my Javascript code, and I need to see whether it's before today or not. Here is the code I have (the relevant part):
todaysDate = new Date();
todaysDate.setHours(0,0,0,0);
var date = Date.parse(row[3]);
// date.setHours(0,0,0,0);
if (date < todaysDate) {
alert("date is before today");
dueDate = '<small class="text-danger">';
} else {
alert("date is after today");
dueDate = '<small class="text-muted">';
}
row[3] is the source of the SQL date. So, this works fine for everything except dates that are today. Without the commented line, it thinks that anything with today's date is in the past. With the commented line, my code breaks. Any thoughts as to how to fix this? Not sure what I'm doing wrong.
Thanks!
If your date string is like "2016-04-10" and your time zone is west of GMT, say -04:00, then in browsers compliant with ECMAScript 2016 you will get a Date for "2016-04-09T19:00:00-0400".
When you create a Date using new Date() and set the hours to zero (assuming it's 10 April where you are), you'll get a Date for "2016-04-10T00:00:00-0400".
So when compared they have different time values.
What you need is to either treat the string you get from the database as local, or get the UCT date where you are, so:
var dateString = '2016-04-10';
var parsedDate = new Date(dateString);
var todayUTCDate = new Date();
todayUTCDate.setUTCHours(0,0,0,0);
document.write(parsedDate + '<br>' + todayUTCDate);
But not all browsers parse strings according to ECMAScript 2015 so they should always be manually parsed. Use a library, or write a small function, e.g.
// Parse date string in format 'yyyy-mm-dd' as local date
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
and replace:
var date = Date.parse(row[3]);
with:
var date = parseISOLocal(row[3]);
and then in the comparison, compare the time values:
if (+date < +todaysDate) {
or
if (date.getTime() < todaysDate.getTime()) {
Use getTime() of date object.
The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
You can compare miliseconds and do your operations
date.getTime() > todaysDate.getTime()
Also be sure that Date.parse is returning a valid date.

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

jQuery how can you verify date formatted mm/dd/yyyy is not greater than current date today

How do I verify in jQuery that a date entered on a input text box or value in html such as mm/dd/yyyy is not greater than todays date. Example would be "5/5/2011" would pass as true b/c its not greater than today "6/17/2011", but "5/5/3011" would be greater than today and should return false. Is there a simple function that can return true or false if a date in form "mm/dd/yyyy" is greater than todays date in javascript or jQuery?
Just convert to a Date object and compare your date value to Date.now - for example:
alert( Date.parse("3/1/2012") > Date.now())
You do not actually need to use jQuery for this at all, pure JavaScript is good enough. Please have a look at the docs for Javascript Date for more information.
convert to javascript Date objects to compare.
var d = new Date("5/5/2011")
var d2 = new Date()
var b = d < d2 // << true...
First off, you need to be sure that dates have a universal format. 10/1/2011 is in the future in the US (October 1st, 2011) but in the past in the UK (10th January 2011). If that's satisfied, the below will work just fine:
function greaterThanToday(datestring) {
var today = new Date();
var date = new Date(datestring);
return (date > today);
}
alert("5/5/2011: " + greaterThanToday("5/5/2011"));
alert("5/5/3011: " + greaterThanToday("5/5/3011"));
Don't even need jQuery, just Date objects.
Date.parse("6/17/2011") > Date.parse("5/5/3011")

Categories

Resources