This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 9 years ago.
I know that date format "dd/mm/yyyy" can be achieved like this:
var d = new Date();
var day = d.getDate();
var month = (d.getMonth() +1);
var year = d.getFullYear();
document.write("Today is " +day+ "/" +month+ "/" +year+ "<br>");
Date picker
var x = new Date(document.getElementById("dateSelection"));
However how can I convert those to a single date object so I can then compare it against date picker in a simple statement like this:
if (d > x)
{
document.write("Date from the past");
}
else if (d < x)
{
document.write("Date from the future");
}
else
{
document.write("Date equals today's date");
}
Thanks for help I'm novice at this.
You are passing the dateSelection element to new Date, not its value. Date wants a string as its parameter, not a DOMElement.
Try this:
var x = new Date(document.getElementById("dateSelection").value);
Use a handy dandy prototype to convert the string to a date:
String.prototype.toDate=function(){
var mo = parseInt(this.substr(0,2)) -1
var dy = this.substr(3,2)
var yr = this.substr(6,4)
var dt = new Date(yr, mo, dy, 0, 0, 0, 0)
return dt
}
var s = '01/01/2014'
var d = s.toDate()
Now you have a date and can do date comparisons.
Related
This question already has answers here:
Get String in YYYYMMDD format from JS date object?
(53 answers)
Closed 5 years ago.
Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
i tried:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
a = new Date(userDate);
y = a.getFullYear();
m = a.getMonth();
d = a.getDate();
return y.toString() + m.toString() + d.toString();
}
console.log(formatDate("12/31/2014"));
where is the problem??
The issue is that getMonth() returns a month index from 0 to 11, so December appears as 11 and not 12.
String#split() the date on / and then concat the generated date, month and year.
function AddLeadingZero(num) {
return (num < 10 ? '0' : '') + num;
}
function formatDate(userDate) {
var [month, day, year] = userDate.split('/');
return year + AddLeadingZero(month) + AddLeadingZero(day);
}
console.log(formatDate("12/31/2014"));
console.log(formatDate("10/1/2014"));
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
return dateParts[3] + dateParts[1] + dateParts[2];
}
var inDate = "12/31/2014";
var outDate = convertDate(inDate);
alert(outDate);
This question already has answers here:
String split returns an array with more elements than expected (empty elements)
(11 answers)
When i try to parse by js split the first element is empty string
(1 answer)
Closed 5 years ago.
I have a bit of code that takes a user input string date MM/DD/YYYY and refactors it to YYYYMMDD, then returns the refactored string.
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var dateParts = userDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
var day = dateParts[2],
month = dateParts[1],
year = dateParts[3];
console.log(dateParts.length);
for (var i = 0; i < dateParts.length; i++) {
console.log(dateParts[i]);
}
console.log(dateParts);
if (day > 0 && day <= 9)
day = 0 + day;
if (month > 0 && month <= 9)
month = 0 + month;
return year + month + day;
}
console.log(formatDate("12/31/2014"));
jsfiddle link
At first I thought that string.split() was returning a 1-based array, but then I discovered that in fact it's returning an array of length 5, with empty strings at userDate[0] and userDate[4] and I can't figure it out. Why is this happening? thanks!
This should work.
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
console.log(userDate);
var dateParts = userDate.split("/");
return dateParts[2] + dateParts[0] + dateParts[1];
}
console.log(formatDate("12/31/2014"));
Two issues here
Replace the regex for split with /\//
Reduce the index of each of the items
i.e.
var day = dateParts[1],
month = dateParts[0],
year = dateParts[2];
Demo
function formatDate(userDate) {
var dateParts = userDate.split(/\//);
var day = pad0(dateParts[1]), month = pad0(dateParts[0]), year = dateParts[2];
return year + month + day;
}
function pad0(input)
{
return ("0" + input).slice(-2);
}
console.log(formatDate("12/31/2014"));
This question already has answers here:
How to add number of days to today's date? [duplicate]
(16 answers)
Closed 8 years ago.
i have the date 2013-12-28 and i want add one or more more day to it. so if i add one more day it will be 2013-12-29.
i try to add it by adding the value of it's date (date 28+1), it works, but what if i add 7 more day to it? the date will be 35, and of course it is not a valid date format.
can someone help me?
here's the example of my script:
var d = new Date();
var Y = d.getFullYear();
var M = d.getMonth()+1;
var D = d.getDate();
var DT = d.getDate()+1;// what if i + 20 days from today? the format would be invalid
var today = Y+"-"+M+"-"+D;
var tomorrow = Y+"-"+M+"-"+DT;
alert(today+" <> "+tomorrow);
// "<>" means nothing
You may try like this using getdate(), setdate() and getdate():
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
If you already have a date object as in the code you show:
var d = new Date();
...then you can add 7 days to it like this:
d.setDate( d.getDate() + 7 );
...and it will automatically increment the month if needed.
Further reading:
The Date object
.getDate() method
.setDate() method
If you need to extract the year, month and day in order to format the result a particular way do so after adding days.
The solution is to convert your date string into unix timestamp, and them add 3600 * 24 * <number of days> to the timestamp and them convert it back to date string.
The code can be as follows:
function addDaysToDate(date, days) {
var time = Date.parse(date) + days * 24 * 3600;
date = new Date(time);
return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
}
var date = '2013-12-28';
console.log(addDaysToDate(date, 7));
I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}
I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012"; // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}