I am facing one issue. I need to compare the given date with the today date using Javascript. I am explaining my code below.
function getCurrentDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = dd+'-'+mm+'-'+yyyy;
return today;
}
var givendate=new Date('19-01-2018');
var todaydate=$scope.getCurrentDate();
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}
Here I should get the result true but here I am getting the console message as false. Please help me to resolve this issue.
The below code works. Like the others said, you need to ensure that you are specifying the date in the proper format as expected by the Date constructor.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="today"></p>
<p id="text"></p>
<script>
today = new Date();
jan19 = new Date('2018-01-19')
document.getElementById("demo").innerHTML = jan19;
document.getElementById("today").innerHTML = today;
if (today < jan19) {
document.getElementById("text").innerHTML = 'true';
}
else {
document.getElementById("text").innerHTML = 'false';
}
</script>
</body>
</html>
As you said in the comments givendate is "Invalid Date" - that's why you have false.
So, before parsing a date, check how to detect invalid date
new Datetries to parse following ISO 8601 format. Quoting:
The formats are as follows. Exactly the components shown here must be present,
with exactly this punctuation. Note that the "T" appears
literally in the string, to indicate the beginning of the time
element, as specified in ISO 8601.
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Make sure you pass a correctly formatted date when constructing a date object. All the details you need on the subject can be found in JS MDN, on the Date.parse topic
If you want to continue with your current date format(dd-MM-yyyy), then you may need to split the string by - and rearrange accordingly to make a valid date.
JS Code
function getCurrentDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10)
dd = '0' + dd;
if (mm < 10)
mm = '0' + mm;
today = dd + '-' + mm + '-' + yyyy;
return today;
}
var todayDate = getCurrentDate().toString();
var givenDate = '19-01-2018';
var todayDateArray = todayDate.split('-');
var givenDateArray = givenDate.split('-');
todayDate = new Date(todayDateArray[2] + '-'
+ todayDateArray[1] + '-'
+ todayDateArray[0]);
givenDate = new Date(givenDateArray[2] + '-'
+ givenDateArray[1] + '-'
+ givenDateArray[0]);
if(givenDate >= todayDate)
console.log('bool', true);
else
console.log('bool', false);
This works for me. If you don't want a custom formatted date then you can use this.
function getCurrentDate(){
var today = new Date();
return today;
}
var givendate=new Date("2018-01-19");
var todaydate= getCurrentDate();
console.log(givendate);
console.log(todaydate);
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}
Related
so I got this function that adds 5 days to the current date, the only problem is that the date is displayed as "Mon May 30 2022 00:16:04 GMT+0300 (Eastern European Summer Time)" I need a simple, clean format like 22/07/2002.
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
ar d = new Date();
d.setDate(d.getDate() + 10);
document.getElementById("date").innerHTML = d ;
SUGGESTION
You can use formatDate(date, timeZone, format) method to easily format date objects. See this quick sample below:
SCRIPT
function test() {
var d = new Date();
var formattedDate = Utilities.formatDate(new Date(d.setDate(d.getDate() + 5)), Session.getScriptTimeZone(), "dd/MM/yyyy")
console.log(formattedDate);
}
Demo:
date.toISOString().slice(0, 10): Convert date to string and get first 10 character.
toISOString() (2022-05-29T23:03:31.782Z to 2022-05-29)
date.split('-').reverse().join('/'): Split string by -, reverseit for formatting and convert array to a string with / separator. (2022-05-29 to 29/05/2022)
const addDays = (days) => {
let date = new Date();
date.setDate(date.getDate() + days);
date = date.toISOString().slice(0, 10);
return date.split('-').reverse().join('/');
}
const date = addDays(5);
console.log(date);
Format Date and add days to it
function formatDate(days = 10) {
const dt = new Date();
Logger.log(Utilities.formatDate(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate() + days),Session.getScriptTimeZone(),"dd/MM/yyyy"));
}
Execution log
5:11:55 PM Notice Execution started
5:11:54 PM Info 03/06/2022
5:11:56 PM Notice Execution completed
Try this
// Note this wont calculate 5days ahead ,it just gives the asked format!
var today = new Date();
var dd = String(today.getDate()).padStart(2,'0');
to the current date
var mm = String(today.getMonth()+1).padStart(2,'0');
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
console.log(today);
This should work if the days overflow with the months.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add Days to Date</title>
</head>
<body>
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
<script>
//Date class
var d = new Date();
//Returns the current day
var day = d.getDate();
//Returns the current month
var month = d.getMonth();
//Returns the current year
var year = d.getFullYear();
//New Date Class for the current date plus added days
//Days overflowing will make a new month and a new year if needed
//see "https://www.w3schools.com/js/js_dates.asp" for more info
var newDate = new Date(year, month, day+5);
//month indexes are 0-11 for Jan-Dec, so the added one is necessary
var dd = newDate.getDate();
var mm = newDate.getMonth()+1;
var yyyy = newDate.getFullYear();
//for the double digit string
dd = dd.toString().padStart(2,"0");
mm = mm.toString().padStart(2,"0");
//Date string Message
var dateString = `${dd}/${mm}/${yyyy}`;
document.getElementById("date").innerHTML = dateString;
</script>
</body>
</html>
I have been trying to subtract date format (yyyy-MM-dd) to another date format but to no avail. I looked up online but it's confusing and I got this error which says that is it not a function for today.getDate(). Could anyone provide me with a solution in subtracting? I am at my wits end.
Thanks in advance.
for (var i = 0; i < 3; i++) {
var startDate = "2020-08-19"
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
today.setDate(today.getDate() - startDate);
console.log(today.getDate() - startDate);
if ((startDate - today) >= 30) {
console.log("hello");
} else if ((startDate - today) <= 30) {
console.log("bye");
}
};
You are mixing a few concepts:
var today = new Date();
This creates a Date object that wraps the number of milliseconds from 1/1/1970 at midnight UTC.
today = yyyy + '-' + mm + '-' + dd;
This is creating a string.
If your goal is to find out how many days are between two dates, your best bet is to use milliseconds since Unix epoch, sometimes called "Unix timestamps." With these timestamps, subtracting is straightforward since they're just numbers; you'll get the number of milliseconds between the two points of time. Getting from timestamps to number of days then becomes a matter of division:
const diff = Date.now() - Date.parse("2020-08-19");
const numDays = diff / (1000 * 60 * 60 * 24);
I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo
Good afternoon in my timezone.
I want to compare two dates , one of them is inserted by the user and the other is the present day. Snippet of code :
var dateString = "2012-01-03"
var date = new Date(dateString);
date < new Date() ? true : false;
This returns true, i think under the hood both Date objects are transformed to milliseconds and then compared , and if it is this way the "Today" object is bigger because of the hours and minutes.So what i want to do is compare dates just by the day month and year.What is the best approach ? Create a new Date object and then reset the hours minutes and milliseconds to zero before the comparison? Or extract the day the month and year from both dates object and make the comparison ? Is there any better approach ?
Thanks in advance
With the best regards.
Happy new year
Set the time portion of your created date to zeros.
var d = new Date();
d.setHours(0,0,0,0);
Since it's in yyyy-mm-dd format, you can just build the current yyyy-mm-dd from date object and do a regular string comparison:
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth()+1;
if (month < 10) month = "0" + month;
var day = currentDate.getDate();
if (day < 10) day = "0" + day;
currentDate = year + "-" + month + "-" + day;
var dateString = "2012-01-03"
var compareDates = dateString < currentDate ? true : false;
document.write(compareDates);
A production-ready example based on top of Accepted Answer
Add the following function to your Javascript
Date.prototype.removeTimeFromDate = function () {
var newDate = new Date(this);
newDate.setHours(0, 0, 0, 0);
return newDate;
}
Invoke it whenever you wish to compare
firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()
I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.
For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.
Simply:
yourDate.setDate(yourDate.getDate() - daysToSubtract);
function date_by_subtracting_days(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Never go for this solution
yourDate.setDate(yourDate.getDate() - daysToSubtract);
it wont work in case your date is 1st of any month and you want to delete some days say 1.
Instead go for below solution which will work always
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Here i am posting one more answer and that will return date in specific format.
First you can get current date 10/08/2013 as below
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
alert("current_date"+current_date);
Back_date();
}
Now Get back date base on X days
function Back_date()
{
var back_GTM = new Date(); back_GTM.setDate(back_GTM.getDate() - 2); // 2 is your X
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth()+1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' +b_mm
}
var back_date= b_mm + '/' + b_dd + '/' + b_yyyy;
alert("back_date"+back_date);
}
So, Today is 10/08/2013 so it will return 10/06/2013.
Check Live Demo here
Hope this answer will help you.
Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.
function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}
This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Just another option, which I wrote:
DP_DateExtensions Library
It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.
this is in reference to above answer
check this fiddle
https://jsfiddle.net/uniyalguru/azh65aa0/
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");