有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
另一种比较两个日期的方法是通过toISOString()方法。这在与保存在字符串中的固定日期进行比较时特别有用,因为可以避免创建短时间对象。借助ISO 8601格式,您可以按字典方式比较这些字符串(至少在使用相同时区时)。
我不一定说它比使用时间对象或时间戳更好;只是将此作为另一种选择。这可能会失败,但我还没有发现:)
其他回答
function compare_date(date1, date2){
const x = new Date(date1)
const y = new Date(date2)
function checkyear(x, y){
if(x.getFullYear()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getFullYear()<y.getFullYear()){
return "Date2 > Date1"
}
else{
return checkmonth(x, y)
}
}
function checkmonth(x, y){
if(x.getMonth()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getMonth()<y.getMonth){
return "Date2 > Date1"
}
else {
return checkDate(x, y)
}
}
function checkDate(x, y){
if(x.getDate()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getDate()<y.getDate()){
return "Date2 > Date1"
}
else {
return checkhour(x,y)
}
}
function checkhour(x, y){
if(x.getHours()>y.getHours()){
return "Date1 > Date2"
}
else if(x.getHours()<y.getHours()){
return "Date2 > Date1"
}
else {
return checkhmin(x,y)
}
}
function checkhmin(x,y){
if(x.getMinutes()>y.getMinutes()){
return "Date1 > Date2"
}
else if(x.getMinutes()<y.getMinutes()){
return "Date2 > Date1"
}
else {
return "Date1 = Date2"
}
}
return checkyear(x, y)
嗨,这是我比较日期的代码。在我的情况下,我正在检查是否允许选择过去的日期。
var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();
if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
isPastPickupDateSelected = false;
return;
}
}
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;
from_date ='10-07-2012';
to_date = '05-05-2012';
var fromdate = from_date.split('-');
from_date = new Date();
from_date.setFullYear(fromdate[2],fromdate[1]-1,fromdate[0]);
var todate = to_date.split('-');
to_date = new Date();
to_date.setFullYear(todate[2],todate[1]-1,todate[0]);
if (from_date > to_date )
{
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
return false;
}
使用此代码使用javascript比较日期。
谢谢D.吉普
If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)
如果两个日期相同,则返回TRUE,否则返回FALSE
const compareDate = (dateVal1, dateVal2) => {
if (dateVal1.valueOf() === dateVal2.valueOf()){
return true;
}
else { return false;}
}
什么格式?
如果您构造了Javascript Date对象,您可以将它们减去以获得毫秒差(编辑:或只是比较它们):
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true