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!
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);
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);
}
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();
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/.
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, "-");