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

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");

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 get tomorrow's date of a specific date

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.

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

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));
}

HTML input prepopulate date

Am rediscovering HTML after quite some time.
I am using just HTML and javascript along with Salesforce. I have two date input fields.
I was curious to see if there is any easy way to populate these fields with:
a. Today's date
b. Date 6 months before today.
<input type="text" id="toDate" size="10" onmouseover="initialiseCalendar(this, 'toDate')"/>
Thanks,
Calvin
The following JavaScript sets the value of your textbox to today's date, in format yyyy-mm-dd. See how I add 1 to the month? getMonth() returns 0-11 for current month, so 1 is added to it:
var today = new Date();
document.getElementById("toDate").value = today.getFullYear() + "-" +
parseInt(today.getMonth()+1) + "-" + ​​​​​​today.getDate();​​​​​
DEMO: Fiddle
It is worth noting though that if the month or day are lower than 10, you'll only get one digit for each of them. Let me know if this is an issue.
EDIT: To get 6 months from today, use:
var today = new Date();
var past = today.setMonth(today.getMonth() - 6);
Populate with today's date:
var today = new Date();
document.getElementById("toDate").value = today.getFullYear() + "-"
+ String(today.getMonth() + 101).slice(-2) + "-"
+ String(today.getDate() + 100).slice(-2);
6 month in the past:
var past = new Date();
past.setMonth(past.getMonth() - 6); //
document.getElementById("toOldDate").value = past.getFullYear() + "-"
+ String(past.getMonth() + 101).slice(-2) + "-"
+ String(past.getDate() + 100).slice(-2);

Categories

Resources