This question already has answers here:
What are valid Date Time Strings in JavaScript?
(2 answers)
Closed 1 year ago.
I have two dates .
var dateOne = "24/04/1995"
var dateTwo = "24/04/1998"
How can i check if one date is bigger than the other?
I tried this :
function myFunction() {
var d1 = Date.parse(dateOne);
var d2 = Date.parse(dateTwo);
if (d1 < d2) {
alert ("Error! Date did not Match");
}
}
but its not working =(
there is a method for this dd/mm/yyyy format?
Relying on the docs around Date
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
You can simply cast to a Number and compare:
const isDateOneBigger = +dateOne > +dateTwo;
However in your case your Dates are invalid. You can check this by logging out d1 which will result in NaN. If you take a look at How to convert dd/mm/yyyy string into JavaScript Date object? you'll see how you can convert your strings into correct dates.
use the getTime() as so
function myFunction() {
var d1 = new Date(dateOne);
var d2 = new Date(dateTwo);
if (d1.getTime() < d2.getTime()) {
alert ("Error! Date did not Match");
}
}
the getTime() method convert the date into milliseconds
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Compare two dates with JavaScript
(43 answers)
Comparing date part only without comparing time in JavaScript
(28 answers)
Closed last year.
I would like to know how to compare any two different date strings in javascript.
Two Date Strings, d1 and d2 are always in the format , dd mmm yyyy and yyyy-mm-dd
How to compare datestring whether is same or not in javascript
Below datestring is example,
var d1 = "12 Feb 1990"
var d2 = "1990-02-12"
if(d1.split(' ').[1] === new Date().toLocaleString('en-US', {month: 'short'})){
return true;
}
else {
return false
}
If you want to compare only the date string then the .toDateString method is all you need. Something like
You can read more about the toDateString method on MDN
let d1 = "12 Feb 1990"
let d2 = "1990-02-12"
const d1String = new Date(d1).toDateString()
const d2String = new Date(d2).toDateString()
if (d1String === d2String) {
console.log('Equal');
} else {
console.log('Not equal');
}
Here's some code that reorders the "1990-02-12" string and compares it to the "12 Feb 1990" one:
function d2ToNormalDate(string) {
return string.split("-")[1] + "-" + string.split("-")[2] + "-" + string.split("-")[0];
}
function areDateStringsEqual(string1, string2) {
// Expects string1 to be a string like "12 Feb 1990" and
// expects string2 to be a string like "1990-02-12".
// returns a boolean.
return new Date(d2ToNormalDate(string2)).toString() === new Date(string1).toString()
}
I need to subtract a date like 1/26/2015 from a date-time like 2016-01-27T01:10:57.569000+00:00. From what I've read converting both to distance in milliseconds from Epoch and then subtracting is the easiest way. I've tried using various methods, but all the methods seem to say 2016-01-27T01:10:57.569000+00:00 is invalid data. The method .getTime() works great for the 1/26/2015 format, but it can't read the 2016-01-27T01:10:57.569000+00:00.
How does one go about getting the date/time UTC time into milliseconds?
On a complicated way you can use a regex to extract each part of the date as string and then use them in a new Date with all parameters:
function getTimeDifference(){
var regEx = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([\d.]+)/;
var dateString = '2016-01-27T01:10:57.569000+00:00';
var r = regEx.exec( dateString );
var date1 = new Date(r[1], r[2]-1, r[3], r[4], r[5], r[6]); // Notice the -1 in the month
var date2 = new Date('1/26/2015');
var difference = date1 - date2;
Logger.log(difference);
}
I ended up using this. When I call parseDate(), I used getTime() to get the date in milliseconds then subtracted them and converted them to days. For my use case the time didn't have to be down to the second, but if it did, it wouldn't be hard to parse more info from the string. I ran into trouble initially because as a beginner Javascript writer I didn't know why apps script wouldn't accept this format into the date constructor.
function parseDate(str) {
//This should accept 'YYYY-MM-DD' OR '2016-01-27T01:10:57.569000+00:00'
if(str.length == 10){
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
else
{
var mdy = str.split('-');
var time = mdy[2].split('T');
var hms = time[1].split(':');
return new Date(mdy[0], mdy[1]-1, time[0], hms[0], hms [1]);
}
}
If you are confident that the values in the date strings will always be valid and that the ISO8601 string will always have offset 00:00 (i.e. UTC), then simple parse functions are:
// Parse ISO 8601 format 2016-01-27T01:10:57.569000+00:00
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5],b[6]));
}
document.write(parseISOUTC('2016-02-04T00:00:00.000+00:00'));
// Parse US format m/d/y
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2],b[0]-1,b[1]);
}
document.write('<br>'+ parseMDY('2/4/2016'))
document.write('<br>'+ (parseISOUTC('2016-02-04T00:00:00.000+00:00') - parseMDY('2/4/2016')))
Note that the first string is UTC and the second will be treated as local (per ECMAScript 2015), so the difference between 2016-02-04T00:00:00.000+00:00 and 2/4/2016 will be the time zone offset of the host system.
I am facing some problem in comparing dates in javascript.
I have dates in "1-Dec-2014" & "19-Nov-2014" format.
While I compared the dates like
var stDate='19-Nov-2014';
var endDate='1-Dec-2014';
if(stDate < endDate){
console.log('Hi');
}else{
console.log('Bye');
}
In out put it shows me "Bye", but it should be "Hi".
What I observed it this comparison compares the date (initial argument) in respective dates.
I am very new to javascript . I am not getting any way to solve this .
Please help me.
Currently you are only comparing two strings. You should compare the dates like this:
new Date(stDate) < new Date(endDate)
var stDate='19-Nov-2014';
var endDate='1-Dec-2014';
if(new Date(stDate) < new Date(endDate)){
console.log('Hi');
}else{
console.log('Bye');
}
Just like #Arun P Johnny said, you are comparing Strings instead of actual dates. You need to convert you date to Date objects before comparing them. Check this out.
As noted in other answers, you need to convert the strings to Date objects. The best way to do that is to parse the strings using a function like:
/* Return a Date object or NaN given a string in d, MMM y or dd-MMM-yyyy format
** e.g. 5 Dec, 2014
** Avoid conversion of two digit dates to 20th century
** Returns NaN if string is not a valid date
*/
function parseDMMMY(s) {
var b = s.match(/\w+/g);
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
if (b) {
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], months[b[1].toLowerCase()], b[0]);
}
return b && d.getFullYear() == b[2] && d.getDate() == b[0]? d : NaN;
}
This also treats dates like 1-1-19 as in year 19, rather than 1919 which may happen if the values are passed directly to the Date constructor rather than using the set* methods.
Now you can do:
var stDate = parseDMMMY('19-Nov-2014');
var endDate = parseDMMMY('1-Dec-2014');
To handle dates correctly i'll quote Pavel Hodek
The best you can do is use the ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
For example:
new Date('2011-04-11')
or
new Date('2011-04-11T11:51:00')
For more Info: MDN | Date
Edit:
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')
Note that the number of the month must be 1 less.
Important note:
The "ISO format" solution doesn't work 100% time. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). Calling toString returns the local time therefore depending on the users timezone in some cases new Date('2011-04-11') will give you 2011-04-10.
Chrome behaves the same as Internet Explorer 9 and Firefox behaves the same as Internet Explorer 10+.
Safe solution is passing string value with Z to be parsed as UTC value e.g. new Date('2011-04-11T10:20:30Z'). Best practice should always be to store dates as UTC and make computations as UTC. Only for presentation they should be presented as local time.
Once you have both dates (after parsing and/or using constructor) you can safely compare them.
function ValidateDate() {
var SDate = document.getElementById('<%=sdate.ClientID%>').value;
var EDate = document.getElementById('<%=edate.ClientID%>').value;
var sdate = new Date(stDate);
var Edate = new Date(endDate);
var alertReason1 = 'To Date must be greater than or equal to From Date.'
//var endDate = new Date(EDate);
//var startDate = new Date(SDate);
if (SDate != "" && EDate != "" && Edate > sdate ) {
alert(alertReason1);
return false;
}
}
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I have two date strings in DDMMYYYY format. say startdate="18/02/2013" and enddate ="26/02/2013".
How can I compare these dates. I want enddate to be greater than or equal to startdate
Thanks for Your Time.
I'm a fan of moment.js and consider it a core part of my toolkit whenever I have to deal with dates and times - especially when any form of parsing or formatting is involved.
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}
Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc :
month : Integer value representing the month, beginning with 0 for January to 11 for December.
var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks