Get motherday date in format dd.mm.yyyy - javascript

I've tried to get the mother day date (first sunday of may) by Javascript. But the result of my code is 0.4.2021. Where is the fault or there a much more simplier way to get the mothers day date (dd.mm.yyyy) (german time zone).
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDay() + "." + mothersDay.getMonth() + "." + mothersDay.getFullYear());

Here's the proper way of doing this, without error-prone calculations or string concatenation, including formatting it as DD.MM.YYYY:
// Mother's Day is the second sunday in May
const d = new Date();
d.setMonth(4); // May
d.setDate(8); // May 8 is the earliest possible date
// while not a sunday, move to next day
while (d.getUTCDay()) d.setDate(d.getDate() + 1);
const result = new Intl.DateTimeFormat('de-DE', { day: "2-digit", month: "2-digit", year: "numeric"}).format(d);
document.body.innerHTML += result;

getMonth() is 0 based so you need to add 1 to that. Also you want to use getDate() instead of getDay() to get the day value of the date.
I assume you want to get the 2nd sunday of may since the line below from your code adds 7 days. If you want the first sunday you should remove this line too.
mothersDay.setDate(firstSunday.getUTCDate() + 7);
var currentYear = new Date().getFullYear()
var mayFirst = new Date(currentYear + '-05-01');
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek === 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date();
firstSunday.setDate(1 + (7 - dayOfWeek));
}
var mothersDay = new Date(firstSunday);
mothersDay.setDate(firstSunday.getUTCDate() + 7);
mothersDay = new Date(mothersDay);
console.log(mothersDay.getDate() + "." + (mothersDay.getMonth() + 1) + "." + mothersDay.getFullYear());

Related

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.

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

how to Add 1 year to startdate to get the end date in javascript

want a output like below
if Start Date is "01-03-2016" the End date should be "28-02-2017"
if Start Date is "10-04-2016" the End date should be "09-04-2017"
I tried below code
if (dat <= 31 && dat >= 1 && month <= 12 && month >= 1) {
var expiryDate = new Date(n1, month - 1, dat);
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
var day = ('0' + expiryDate.getDate()).slice(-2);
var month1 = ('0' + (expiryDate.getMonth() + 1)).slice(-2);
var year = expiryDate.getFullYear();
var month = getMonthName(month1);
var wholeenddate = day + "-" + month + "-" + year;
but it's not produce desired output.Please Help to solve it.
Add 364 days to your date
For example
var d = new Date("2016-03-01");
d.setDate(d.getDate()+364); //outputs 28-02-2017
and
var d = new Date("2016-04-10");
d.setDate(d.getDate()+364); //outputs 09-04-2017
or Just add 1 year and sub 1 day.
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
Now it will match your output just the same even for leap year :)
Demo
var d = new Date("2016-03-01");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
document.body.innerHTML += "<br>";
d = new Date("2016-04-10");
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate()-1);
document.body.innerHTML += d.toString();
There's a convenient library to help with this sort of thing - moment.js (14k zipped).
var startDate = moment('01-03-2016', 'DD-MM-YYYY');
console.log(startDate.format('DD-MM-YYYY'));
var endDate = startDate.clone();
endDate.add(1, 'years').subtract('1', 'days');
console.log(endDate.format('DD-MM-YYYY'));
3 ways to do this.
// Add hours
var today = new Date();
today.setHours(today.getHours()+24*364);
// Add days
var nextyearDate = new Date();
nextyearDate.setDate(today.getDate()+364);
// More reliable way : Add year & subtract a day.. Hope this works...! Works for 01/01/2016
var nextDate = new Date();
nextDate.setYear(nextDate.getFullYear()+1);
nextDate.setDate(nextDate.getDate()-1);

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: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

Categories

Resources