How to get tomorrow's date of a specific date - javascript

I am trying to get tomorrow's date of a specific date using JavaScript in format (yyyy-mm-dd). For example the specific date is 2021-08-31 and I have got this script:
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1],date.split("-")[2])
date.setDate(date.getDate() + 1);
var tomorrows_date_month = date.getMonth()
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
The expected output is:
2021-09-01
But the output of this code is :
2021-9-2

First you don't need split "2021-08-31" to use as date parameter, so just use new Date("2021-08-31");
Second note that you need to use d.getMonth() + 1 and add leading zero if the length is less than 2:
Try this one:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = "2021-08-31"
var date1 = new Date(date);
console.log(formatDate(date1.addDays(1)));

Internally js month is stored as a value between 0 and 11. So you need to minusdate.split("-")[1] by 1. Otherwise, javascript will think that your month is actually September and we know that "2021-09-32" is translated to "2021-10-2", therefore the date is shown as "2".
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1] - 1,date.split("-")[2])
date.setDate(date.getDate() + 1)
var tomorrows_date_month = date.getMonth() + 1
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
Also note that date = new Date("2021-08-31") is enough for converting a string into a Date object.

new Date(new Date(date + 'T00:00Z').getTime() + 86400000).toISOString().substr(0, 10)
The added 'T00:00Z' assures the date is parsed as UTC, to match the UTC timezone used by toISOString(). Adding 86400000 (the number of milliseconds in one day) advances the date without having to fuss with the date field directly.

Related

How to convert a date formatted (YYMMDD) as string but with 00 days?

I have a date formatted as string, eg: 240800. The date format for that string is YYMMDD. With the below code, I can convert the string to date but it doesn't always work in deducting 1 day. I need my output to be a valid date, not with 00 day. So with the date above, it should be converted and formatted to 07/31/2024.
Here's what I got so far.
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
var formattedDate = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
Working:
"240800" = 7/31/2024
All months from 4 to 12
Not Working:
"240100" = 0/31/2024 x
"240200" = 1/29/2024 x
"240300" = 2/31/2024 x
The reason is the date variable parameter in new Date() is counted as 0~11, not the general range,1~12.
So the working answer actually is wrong. It seems like being right just for July and August have 31 days.
The correct way is to firstly deduct 1 month and then calculate it. After all of the process is done, you can add 1 month in the end.
The below is working codes:
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
//deduct 1 month firstly
var month = Number(stringDate.substring(2,4))-1;
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
//add 1 month finally
var formattedDate = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
formatDate('240100');
In python Assuming your string is yymmdd below function should do what you want. I am sure javascript has some module for date handling.
from datetime import datetime, timedelta
def fd(s):
d=datetime.strptime(s[:-2],'%y%m')+timedelta(days=int(s[-2:])-1)
return d.strftime('%m/%d/%Y')
Try this ..
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var d1;
if (day==="00")
{
d1 = new Date(month + '/01/20' + year);
d1.setDate(d1.getDate() -1);
//console.log("day1" + d1);
}
else
{
d1 = new Date('20' + year, month, day);
}
var formattedDate = d1.getMonth() + '/' + d1.getDate() + '/' + d1.getFullYear();
console.log(formattedDate);
}

how to shift a date to the following month (fixed day)

I have a date in javascript that is dd/mm/yyyy format.
I wanto to calculate from that date another date with the following requisites:
month will be the following from the date chosen (january will shift to february, dicember to january and so on)
year will shift accordingly
day will be always 16
I am starting from this (ref. this question):
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
console.log("Date after 1 months:", CurrentDate);
but need to set the day as 16 and to check that the edge situations are considered.
Any suggestion on how to go on with this code?
P.S. i'm looking for a solution in Vanilla JS or jQuery with no additional libraries
Try this..
function getDate16(d) {
var date1 = d.split('/');
var formattedDate1 = date1[2] + '-' + date1[1] + '-' + date1[0] + 'T00:30:00.000Z';
var CurrentDate = new Date(formattedDate1);
CurrentDate.setDate(16);
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
// Date formatting
var date = CurrentDate.toISOString();
var arr = date.substring(0, 10).split("-");
date = arr[2] + '/' + arr[1] + '/' + arr[0];
console.log("ISO format=", CurrentDate);
console.log("dd/mm/yyyy format=", date);
}
getDate16("28/11/2019");
getDate16("31/12/2019");
getDate16("16/01/2020");

Converting string m/dd/yyyy HH:MM:SS to date dd-mm-yyyy in Javascript

I have a string that looks like '1/11/2018 12:00:00 AM' and I want to reformat it to dd-mm-yyyy.
Keep in mind that the month can be double digit sometimes.
You can use libraries like moment.js. Assuming either you do not want to use any external library or can not use it, then you can use following custom method:
function formatDate(dateStr) {
let date = new Date(dateStr);
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return day + '-' + month + '-' + year;
}
console.log(formatDate('1/11/2018 12:00:00 AM'));
You can do somethink like this :
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
However best way is with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
function convertDate(oldDate) {
var myDate = new Date(Date.parse(oldDate)); //String -> Timestamp -> Date object
var day = myDate.getDate(); //get day
var month = myDate.getMonth() + 1; //get month
var year = myDate.getFullYear(); //get Year (4 digits)
return pad(day,2) + "-" + pad(month, 2) + "-" + year; //pad is a function for adding leading zeros
}
function pad(num, size) { //function for adding leading zeros
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
convertDate("1/11/2018 12:00:00 AM"); //11-01-2018
Demo here

javascript date of specific day of the week in MM/dd/yyyy format not libraries

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}

JavaScript date: How to add a year to a string that contains mm/dd?

I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)

Categories

Resources