I was using moment.js to calculate the next week start date and end date. but right now i have removed it because of some minification issue.
I am able to get this week's start and end date as follows,
var today = new Date;
var first = today.getDate() - today.getDay();
(this.fromDate = new Date(today.setDate(first)));
(this.toDate = new Date(today.setDate(last)));
how to find next week start and end date?
You can achieve this using getFullYear(),getMonth() and getDate() methods.
function getWeekBegin() {
var now = new Date();
var next = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(7 - now.getDay()));
return next;
}
var firstDay = getWeekBegin();
console.log("First day: "+firstDay);
var lastDay=firstDay.setDate(firstDay.getDate() + 6);
console.log("Last day: "+new Date(lastDay));
Just sum 7 days to the start of this week to get the start of the next week; to get the end of the week add 6 days to the start of the week.
var date = new Date;
var nextWeekStart = date.getDate() - date.getDay() + 7;
var nextWeekFrom = new Date(date.setDate(nextWeekStart));
var nextWeekEnd = date.getDate() - date.getDay() + 6;
var nextWeekTo = new Date(date.setDate(nextWeekEnd));
console.log('nextWeekFrom: ' + nextWeekFrom.toString())
console.log('nextWeekTo : ' + nextWeekTo.toString())
Not 100% what your after, but if you modify this a little you should be able to figure out how
function test() {
var today = new Date;
alert(getMonday(today));
}
function getMonday( date ) {
date.setHours((24*7));
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
Just edited the answer, this should get you next mondays date
The following simplifies the code and provides some explanation. The setDate method modifies the date and returns the new time value, so it can be used to modify a date and create a copy in one go.
// Get current date
var d = new Date();
// Set to next Sunday and copy
var startOfWeek = new Date(d.setDate(d.getDate() + 7 - d.getDay()));
// Set to the following Saturday
d.setDate(d.getDate() + 6);
console.log('Start of week: ' + startOfWeek.toString());
console.log('End of week : ' + d.toString());
// The following shows the dates formatted and in the host default language
// Support for toLocaleString options may be lacking though
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log('Start of week: ' + startOfWeek.toLocaleString(undefined, options));
console.log('End of week : ' + d.toLocaleString(undefined, options));
Related
How can I get the day that the next month starts on? (Monday Tuesday etc.).
I tried the following but it returns more than just the day.
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
You're almost there, just add this after your last line of code to get the name of the day
var dayName = lastDay.toLocaleDateString('en-us', { weekday: 'long' });
Also keep in mind that Date constructor's second parameter is monthIndex MDN.
You should add m by 1 to get next month's first day and add it by 2 and provide date = 0 to get the last day of the next month.
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m + 1, 1);
var lastDay = new Date(y, m + 2, 0);
var firstDayName = firstDay .toLocaleDateString('en-us', { weekday: 'long' });
var lastDayName = lastDay.toLocaleDateString('en-us', { weekday: 'long' });
console.log(firstDayName, lastDayName)
Your current code is getting Date instances for the first and last day of the current month. So first you'll need to fix that. Then, if you want day numbers instead, you have to call getDay to get the values (0 = Sunday through 6 = Saturday):
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1; // + 1 = next month
const firstDay = new Date(year, month, 1).getDay();
const lastDay = new Date(year, month + 1, 0).getDay();
console.log({firstDay, lastDay});
As I write this on July 31st, that shows 1 and 3, telling us that August 2022 starts on Monday and ends on Wednesday.
I just took the current date and got the first day of the month. Then we just converted this to string. It's working. Try this:
const date = new Date(); // current date 1/8/2022
const nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1); //first day of next month
const nextMonthStartDay = nextMonth.toLocaleDateString('en-US', { weekday: 'long' }); //convert to date string
console.log(nextMonthStartDay) //Thursday
I have unixtimestamp value 1628312400000 // 7th Aug 2021
var selectedDate = moment(1628312400000);
let formattedDate = moment.tz(day, "America/Chicago").format('DD-MM-YYYY')+ " " +"00:00:00"; //07-08-2021 00:00:00
Now, I want the previous day and the next day of the same timestamp.
So, I tried as below,
let nextDay = moment(selectedDate).add(2, 'days').valueOf();//1628398800000
let yesterDay = moment(selectedDate).subtract(1, 'days').valueOf();// 1628226000000
let yest = "Yesterday :: "+moment.tz(yesterDay, "America/Chicago").format('DD-MM-YYYY')+ " " +"00:00:00";// getting invalid date
let next = "Next Day :: "+moment.tz(nextDay, "America/Chicago").format('DD-MM-YYYY')+ " " +"23:00:00";// getting invalid date
I am getting the output as ,
Yesterday :: Invalid date 00:00:00
Next Day :: Invalid date 00:00:00
expected result
Yesterday :: 06-08-2021 00:00:00
Next Day :: 09-08-2021 23:00:00
Kindly, help/guide me where I am doing the mistake here. Thanks in advance.
Here's how, just add and subtract directly using your selectedDate
var selectedDate = moment(1628312400000);
let next = "Next Day :: " + moment(selectedDate, "America/Chicago").add(2, 'days').format('DD-MM-YYYY') + " " + "23:00:00"; // getting invalid date
let yest = "Yesterday :: " + moment(selectedDate, "America/Chicago").subtract(1, 'days').format('DD-MM-YYYY') + " " + "00:00:00"; // getting invalid date
console.log(yest)
console.log(next)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>
You could get the date from millisecs and store it into selectedDate; then add and subtract starting from this Date:
var selectedDate = new Date(moment(1628312400000));
console.log(moment(selectedDate).add(2, 'days').format('DD-MM-YYYY hh:mm:ss'));
console.log(moment(selectedDate).subtract(1, 'days').format('DD-MM-YYYY hh:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
You could format the given timestamp by chaining methods to get previous day and the next day date values.
let selectedDate = moment(1628312400000);
let formattedDate = moment.tz(selectedDate, "America/Chicago").format("DD-MM-YYYY hh:mm:ss");
let nextDay = moment.tz(selectedDate, "America/Chicago")
.add(1, "days")
.format("DD-MM-YYYY hh:mm:ss");
let yesterDay = moment
.tz(selectedDate, "America/Chicago")
.subtract(1, "days")
.format("DD-MM-YYYY hh:mm:ss");
console.log("Previous", yesterDay);
console.log("Current", formattedDate);
console.log("Next", nextDay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
You my use this functions to your problem
var PropsDataSelected = '2021-08-01' // this will be the user data selected
var date = new Date(PropsDataSelected); // this will set the selected date
Date.prototype.Nextday = function(days) { // this will add days to the selected data
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
Date.prototype.PrevDay = function(days) { // this will remove days from data selected
var date = new Date(this.valueOf());
date.setDate(date.getDate() - days);
return date;
}
console.log('curr date: ', date); // this is the curr date selected
console.log('next date: ', date.Nextday(1)); // this is the number of days you want to add
console.log('prev date: ', date.PrevDay(1)); // this is the number of days you want to remove
In case you want moment you can use like this:
document.getElementById("dateDisplay").innerHTML = moment().format('YYYY-MM-DD');
var nowPlusOneDay = moment().add('days', 1);
var nowPrevOneDay = moment().subtract('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');
var nowPlusPrevDayStr = nowPrevOneDay.format('YYYY-MM-DD');
console.log('Next: '+nowPlusOneDayStr);
console.log('Prev: '+ nowPlusPrevDayStr);
<div id="dateDisplay"></div>
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());
The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');
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));
}