This question already has answers here:
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 4 years ago.
I have this code which works fine. It gives me todays date in a specific format.
function fetchTime() {
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;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
I'm also trying to get today's date minus 1 month. I thought this would be simple, I just removed the +1. So I have this code:
function fetchTime() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
This gives me the output 2019-00-17 which should be 2018-12-17
Can anyone tell me the right way to do this? My question is specific to getting the date out in the required format, whereas most examples I have seen do not output the right format as part of the date change.
I would separate the formatting from the fetching. You could make your existing formatting function take an optional parameter that defaults to today, so you could call it like you already were for today's date.
function formatTime(date) {
var dateToFormat = date || new Date();
var dd = dateToFormat.getDate();
var mm = dateToFormat.getMonth() + 1;
var yyyy = dateToFormat.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return (yyyy + '-' + mm + '-' + dd);
}
Then you could also call it with today's date minus a month or any other date
formatTime(); //will default to today
var today = new Date();
formatTime(addMonths(today,-1)); //format last month's date
As pointed out by RobG in the comments you would need to implement an addMonths function as in Adding months to a Date in JavaScript
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
For substracting in moment.js:
moment().subtract(1, 'months').format("DD-MM-YYYY")
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
You should subtract months by getting the current month, then subtracting the number of months you want and then updating the date variable like this.
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
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;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
Because your desired format is an ISO 8601 date, you could use JavaScript's .toISOString. You are only concerned with the first 10 characters though (not time), so you'd want to add .substring(0,10).
Date.prototype.toISODateString = function() { return this.toISOString().substring(0,10); }
Date.prototype.addMonths = function(val) { this.setMonth(this.getMonth()+val); return this;}
var date = new Date();
var todayFormatted = date.toISODateString();
console.log(todayFormatted);
var lastMonthFormatted = date.addMonths(-1).toISODateString();
console.log(lastMonthFormatted);
I've made the formatting steps a function called toISODateString() and added it to the Date prototype, which is a fancy way of saying "You can chain .toISODateString() to any Date now".
To set the date back a month, I've used .setMonth(). I also turned this into a function called addMonths.
Use the same code, but remove a month. Example:
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
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;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
Related
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'm struggling to complete the following exercise:
I have to declare a function that should read the birthdate in "dd-MM-yyyy" format, then add 1000 days to it and then return the new date in the same format. Input: 1995-02-25 / Output: 20-11-1997. Hints are given: use setDate(), getDate(), getMonth() and getFullYear(). There is a tool that evaluates the code in five tests. Note according to the tool 21-11-1997 should be the returned value. Normally I should add 999 to seDate().
1) Here I passed the first of five test as I returned the correct output. But I guess the input could not be placed there.
function addDays() {
function formatDate(date) {
let dd = date.getDate();
let MM = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (MM < 10) {
MM = '0' + MM;
}
return dd + '-' + MM + '-' + yyyy;
}
let birthday = new Date('1995-02-25');
let birthDate = formatDate(birthday);
return formatDate(new Date(birthday.setDate(birthday.getDate() + 1000)));
}
console.log(addDays()); // 21-11-1997
2) Here the output is NaN, so the first test is failed, but the forth test is passed. I think due to the fact that I put an argument in the addDays() function that is passed on the variables. But I'm not sure.
function addDays(x) {
function formatDate(date) {
let dd = date.getDate();
let MM = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (MM < 10) {
MM = '0' + MM;
}
return dd + '-' + MM + '-' + yyyy;
}
let y = new Date(x);
let birthday = formatDate(y);
return formatDate(new Date(y.setDate(y.getDate() + 1000)))
}
console.log(addDays("1995-02-25"));
I'm new to JS and programming as a whole. Actually I'm learning JS since two weeks and I've spent half of the time dealing whit this. I would be very grateful if you guys can help me with that. I guess that I've missed something in the algorithm as well in other parts. Thanks in advance!
i am trying to calculate my date to 364 days using javascript, this works as i got a snippet online that functions the way i expect.
But now i have noticed that the date format is in 1 digit.
meaning for the present month instead of september to be written as "09" its wriiten as "9", i am honestly not a javascript king so am looking for help on this.
This is what i am presently trying that gives me a 1 digit date
<script type='text/javascript'>//<![CDATA[
function getdate() {
var tt = document.getElementById('inputDater').value;
var date = new Date(tt);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 364);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById('follow').value = someFormattedDate;
}
//]]>
</script>
so onclick of my button i call my function, please can someone enlighten me thanks
Format the month into 2 digit format using the following method.
mm = ("0" + mm).slice(-2);
var someFormattedDate = y + '-' + mm + '-' + dd;
or use the following function, which is simple and you can use for date too
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
mm = pad(mm);
you can change the line in your code from
var mm = newdate.getMonth() + 1;
to
var mm = newdate.getMonth()<9 ? '0'+(newdate.getMonth()+ 1) : newdate.getMonth()+1;
Hope this helps
function getDate() {
//var tt = document.getElementById('inputDater').value;
var date = new Date();//(tt);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 364);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
//2 digit format
dd = dd.toString().length == 1 ? '0' + dd : dd;
mm = mm.toString().length == 1 ? '0' + mm : mm;
var someFormattedDate = y + '-' + mm + '-' + dd;
console.log(someFormattedDate);
};
getDate();
I am working on JavaScript validation where I am validating whether a textbox date is equal to the current date or not.
If its greater or equal to today's date than do something, if its less than today's date then show error message.
Note: In my textbox I have converted date into dd/MM/yyyy format. So I need to check textbox date with current date in dd/MM/yyy format only. Here is my code:
function ValidateDate() {
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
var Today = new Date();
if(EffectiveDate<Today())
{
//Show Error Message
}
else
{
//Do something else
}
I need the date to be in dd/MM/yyyy format for checking my textbox date, so my Today value has to be in dd/MM/yyyy format only.
function ValidateAddNewCourseCharge() {
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
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
}
var Today = dd + '/' + mm + '/' + yyyy;
dateFirst = EffectiveDate.split('/');
dateSecond = Today.split('/');
var value = new Date(dateFirst[2], dateFirst[1], dateFirst[0]);
var current = new Date(dateSecond[2], dateSecond[1], dateSecond[0]);
if (EffectiveDate == "") {
showErrorMessagePopUp("Please Select a Date for Course Charge!");
return false;
}
else {
if (value < current) {
showErrorMessagePopUp("Date should not be less than Present Date!");
return false;
}
}
return true;
}
First, we have to find the current date -- below is code that finds it. Then, compare the result with the value entered in TextBox.
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 = mm + '/' + dd + '/' + yyyy;
document.write(today);
var EffectiveDate = $.trim($("[id$='txtFromDate']").val());
I think it will help for you
var getdate = new Date($("[id$='txtFromDate']").val());
var curDate = new Date();
alert(getdate - curDate === 0);
alert(getdate - curDate < 0);
alert(getdate - curDate > 0);
Given a day of the week (var day) the code below will print the date of each
day in the year starting from today. Since 4 = Thursday, I will get a list
of all the Thursdays left in the year. I was just curious if there was some
'neater' way to accomplish this?
var day = 4;
var date = new Date();
var nextYear = date.getFullYear() + 1;
while(date.getDay() != day)
{
date.setDate(date.getDate() + 1)
}
while(date.getFullYear() < nextYear)
{
var yyyy = date.getFullYear();
var mm = (date.getMonth() + 1);
mm = (mm < 10) ? '0' + mm : mm;
var dd = date.getDate();
dd = (dd < 10) ? '0' + dd : dd;
console.log(yyyy + '-' + mm + '-' + dd)
date.setDate(date.getDate() + 7);
}
Output:
2011-02-10
2011-02-17
2011-02-24
2011-03-03
2011-03-10
..etc
Well, it would look a lot prettier if you used Datejs.
var thursday = Date.today().next().thursday(),
nextYear = Date.next().january().set({day: 1}),
format = 'yyyy-MM-dd';
while (thursday.isBefore(nextYear))
{
console.log(thursday.toString(format));
thursday = thursday.add(7).days();
}
See also http://code.google.com/p/datejs/.