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">
<a href="javascript:;" onclick="this.href='url?date=' document.getElementById('myDate').value">Submit</a>
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.
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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()
.