How can I change the default start and end of the day? - javascript

So the day starts are 12AM and ends at 11.59.59 PM. I have a use case where I would like to change that behavior and have the day start at say 10 AM and end at 9.59.59.
Is there a way to do this in native javascript date or in moment.js?

Javascript has no concept of "start of day" or "end of day". It creates date objects with a time value based on the provided parameters, that's it.
You could create your own function to return dates for default times. The following creates a date for start of day based on:
If the time is before startOfDay, the start is set to startOfDay on the previous day
Otherwise it's set to startOfDay on the current day.
Similarly for end of day:
If the date is on or after startOfDay, the end is set to endOfDay the following day
Otherwise it's set to endOfDay on the current day
The start and end could be parameterised to set the start and end of day times.
// Return a new date set to 10 hrs
// If the input is before startOfDay, then the date is set
// to the previous day at 10.
function startOfDay(date = new Date(), sod = 10) {
return new Date(date.getFullYear(), date.getMonth(),
date.getDate() + (date.getHours() < sod? -1 : 0), sod);
}
// Return a new date set to 1 second before startOfDay
// If the input is after startOfDay, the date is set to
// tomorrow
function endOfDay(date = new Date()) {
let end = startOfDay(date);
end.setDate(end.getDate() + (end < date? 1 : 0));
end.setSeconds(end.getSeconds() - 1, 0);
return end;
}
// Example
let dates = [
new Date(2023,0,10,9), // Start is on 9 Jan
new Date(2023,0,10,11), // End is on 11 Jan
].forEach(date =>
console.log(`Date : ${date.toLocaleString()}` +
`\nStart: ${startOfDay(date).toLocaleString()}` +
`\nEnd : ${endOfDay(date).toLocaleString()}`
)
);

Related

How to display today's date and time as 9 am and continue till next day?

I am doing a react project.I want to display today's date and time as "9 am" .This has to be remained unchanged till time is 9 am on next day. After that it should display time as 9 am along with date of that day and continue this till next day 9 am and so on.
<span>Last Updated: {moment().format('MMMM Do YYYY,') + " 9:00 am"}</span>
The above code displays the time as 9 am even before the time is 9 am on the nextday. It should look like current time and date gets updated only at 9 am everyday.
This code creates a function that retrieves the formatted date at a given hour. If the hour is not specified, it will use the current hour. It will return today's date, unless the hour is before 9, in which case it will return yesterday's date. The format will use the current user's native formatting for a "long" date. The HTML shows the desired result, the console logs what happens before 9 on the current day, and the current hour. The hour is determined by the user's time zone.
function getDateAtNine(forceHour) {
let now = new Date();
const hour = forceHour == null ? now.getHours() : forceHour;
if (hour < 9) {
now = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
}
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long'
}).format(now);
}
console.log(getDateAtNine(8)); // shows what will print at 8 am on today's date
console.log(getDateAtNine()); // shows what will print at the current hour on today's date
document.querySelector('#dateat9').textContent = getDateAtNine();
<span id="dateat9"></span><span id="nineam">, 9:00 am</span>
Is that what you are looking for? ;)
const getLastStartOfDay = (startOfDayHour) => {
let todayStartOfDay = new Date();
todayStartOfDay.setHours(startOfDayHour, 0, 0, 0);
let yesterdayStartOfDay = new Date(todayStartOfDay);
yesterdayStartOfDay.setDate(yesterdayStartOfDay.getDate() - 1);
let dt = new Date();
const displayDate =
dt.getHours() < startOfDayHour ? yesterdayStartOfDay : todayStartOfDay;
return displayDate;
};
console.log("LastStartOfDay: ", getLastStartOfDay(9));

How to get the 1st date and last date of the current Week as well as Month in the format of 'yyyy-mm-dd' using App Scripts

I am trying to figure out the 1st date and last date of the current week as well as the 1st date and last date of the current month in the format yyyy-mm-dd using Google App scripts. Date() seems to be a difficult object for me, therefore seeking advice. Please consider Saturday is the starting day and Friday is the end day of a week in this parts of the world.
Get first (Saturday) and last (Friday) date of this week
You can use Date.getDay() to get the current day of the week (0=Sunday, 1=Monday, etc.). But there is no method Date.setDay() so we need to do a little math to figure out how many days ago the most recent Saturday was, and use Date.setDate():
// Get the Date for the Saturday on or preceding the current date.
var saturday = new Date(); // Today
var day = date.getDay(); // Day of week (0-6)
var newDay = date.getDate() - ((day + 1) % 7); // The day of the month we want.
saturday.setDate(newDay); // Our date object for Saturday.
(day + 1) % 7 calculates how many days to subtract; for example, if today is Sunday (day=0), we need to go back one day: (0 + 1) % 7 = 1. But if today is Saturday (day=6), we get (6 + 1) % 7 = 0 and we don't subtract any days.
The routine for finding the upcoming Friday is similar, but we add days instead of subtracting:
// Get the Date for the Friday on or after the given date.
var friday = new Date(date); // today
var day = date.getDay();
var diff = date.getDate() + ((5 - day) % 7);
friday.setDate(diff);
Get first and last date of this month
This is simpler using setDate(), since it takes as its parameter the day of the month.
var firstOfMonth = new Date(); // today
firstOfMonth.setDate(1); // Sets the day to the first of the month
To get the last of the month, we go ahead one month, then back to the last day of the previous month (the last of this month):
var lastOfMonth = new Date();
lastOfMonth.setMonth(lastOfMonth.getMonth()+1); // Go ahead one month
lastOfMonth.setDate(0); // Sets to 1 day before the first of the month, i.e. the last of this month.
Convert to format 'yyyy-mm-dd'
Google Apps Script has a built-in method for formatting dates: Utilities.formatDate(date, timezone, format)
date is a Date object, timezone is a string such as those from the TZ database, and format is a string in SimpleDateFormat
For example:
var formattedDate = Utilities.formatDate(friday, 'America/Denver', 'yyyy-MM-dd');
(Note the capital MM for month because mm represents minutes.)
You can use toLocaleString("sv-SE") to convert the date to the desired format yyyy-mm-dd.
Try this:
const today = new Date();
const firstWeekD = today.getDate() - today.getDay()-1;
const lastWeekD = firstWeekD + 6;
const firstdayOfWeek = new Date(today.setDate(firstWeekD)).toLocaleString("sv-SE").slice(0,10);
const lastdayOfWeek = new Date(today.setDate(lastWeekD)).toLocaleString("sv-SE").slice(0,10);
const date = new Date();
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).toLocaleString("sv-SE").slice(0,10);
const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleString("sv-SE").slice(0,10);
console.log(firstdayOfWeek); // first day of the week - Saturday
console.log(lastdayOfWeek); // last day of the week - Friday
console.log(firstDayOfMonth) // first day of the month
console.log(lastDayOfMonth) // last day of the month

How to get the date of a specific day in javascript?

I have a diferent number of days
example (1=monday,2=tuesday.......)
and i need to return the date o this day in the current week
For example: if i send number 3 to my function, in this current week, today is sunday 23 , and i need that my function give me the date of the day 3 in this week, in this case the wednesday day was june-19 .
other example i pass the number 5 to my function the function return me the date of the day 5 this week (friday)= june-21 (2019/06/21)
something like that
let currentDate = new Date().toISOString().slice(0, 10)
The strategy is fairly straight forward:
new Date() gets you the current date
The getDay method returns the day number of the date's day of the week
The getDate method returns the day number of the date's day of the month
The setDate method sets the day number of the date's day of the month
So you get the current date, subtract the current day number, then add the day number you want to the date. This will also wrap to previous and following months, e.g.
/* Given a week day number, return the date for that
* day in the current week.
*
* #param {number} dayNumber - number of day in week.
* If 0, returns Sunday at start of week
* If 7, returns Sunday at end of week
* Otherwise 1 Mon, 2 Tue, etc.
* If not an integer in range 0 to 7 returns undefined
* #returns {number|undefined} date of supplied day number
*/
function getDateForDayInWeek(dayNumber) {
dayNumber = Number(dayNumber);
// Validate input
if (dayNumber < 0 ||
dayNumber > 7 ||
parseInt(dayNumber) != dayNumber) {
return; // undefined
}
let d = new Date();
d.setDate(d.getDate() - d.getDay() + dayNumber);
return d.getDate();
}
// Examples
console.log('Today is ' +
new Date().toLocaleString(undefined, {
month:'long', weekday:'long', day:'numeric'
})
);
// Sample values
[0, // Sunday at start of week
3, // Wednesday
7, // Sunday end of week
23, -2, 2.4 // All invalid, return undefined
].forEach(
n => console.log(n + ':' + getDateForDayInWeek(n))
);
You might want the function to return a Date, then you can do more with it, including just getting the date, but also the month and day name, etc.

How to select first day and last day of the week when we select any date in dojox.calendar.?

I am using a custom dojox.calendar. currently if I select any date I am able to get the date. Now,How to select first day and last day of the week when we select any date in dojox.calendar.?
Here is a small function that, given a Date object and week day number, returns the previous day of the same week day number (Sunday = 0, Monday = 1, …, Saturday = 6).
function getPreviousDay(date, day) {
var d = new Date(+date);
d.setDate(d.getDate() - ((7 + d.getDay() - day) % 7));
return d;
}
console.log(getPreviousDay(new Date(2013,11,24), 2)); // Tue 17-Dec-2013
If the Date is a Tuesday and the week day number is 2, it will return a copy of the supplied Date. This can be used to build functions that, given a Date, return the previous Sunday and next Saturday:
// If date is Sunday, return a copy of date (default for getPreviousDay)
// Otherwise, get previous Sunday
function getPreviousSunday(date) {
var d = getPreviousDay(date, 0);
return d;
}
// If date is Saturday, return a copy of date
// Otherwise, get previous Saturday and add 7 days
function getNextSaturday(date) {
if (date.getDay() == 6) {
return new Date(+date);
}
var d = getPreviousDay(date, 6);
d.setDate(d.getDate() + 7);
return d;
}
var d = new Date(2013,11,21);
console.log(
d + '\n' +
getPreviousSunday(d) + '\n' +
getNextSaturday(d)
);
/*
Sat 21-Dec-2013
Sun 15-Dec-2013
Sat 21-Dec-2013
*/
Those values can then be used to select a date range in the calendar.
I use new Date(+date) to copy dates because otherwise in the years 0 to 99, IE will assume 1900 to 1999 and mess up the copy. While it's unlikely you'll want to use dates in this range (pretty pointless really) it makes me feel better knowing that it will "work" if you do.
IE does this because if a Date object is passed to the Date constructor, it is first converted to a string, then the string parsed to create a Date object. IE incorrectly parses its own string for years 0 to 99. Using + converts the date to a time value, which is treated correctly by the Date constructor everywhere (as far as I know).

JavaScript - get the first day of the week from current date

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - currentDay + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - (currentDay || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
Check out Date.js
Date.today().previous().monday()
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
The solution correctly wraps on months (due to Date.setDate() being used)
For startOfWeek, the same constant numbers as in Date.getDay() can be used
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
It is important to discern between local time and UTC. I wanted to find the start of the week in UTC, so I used the following function.
function start_of_week_utc(date, start_day = 1) {
// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.
date = new Date(date);
const day_of_month = date.getUTCDate();
const day_of_week = date.getUTCDay();
const difference_in_days = (
day_of_week >= start_day
? day_of_week - start_day
: day_of_week - start_day + 7
);
date.setUTCDate(day_of_month - difference_in_days);
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date;
}
To find the start of the week in a given timezone, first add the timezone offset to the input date and then subtract it from the output date.
const local_start_of_week = new Date(
start_of_week_utc(
date.getTime() + timezone_offset_ms
).getTime() - timezone_offset_ms
);
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
Accepted answer won't work for anyone who runs the code in UTC-XX:XX timezone.
Here is code which will work regardless of timezone for date only. This won't work if you provide time too. Only provide date or parse date and provide it as input. I have mentioned different test cases at start of the code.
function getDateForTheMonday(dateString) {
var orignalDate = new Date(dateString)
var modifiedDate = new Date(dateString)
var day = modifiedDate.getDay()
diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
modifiedDate.setDate(diff)
var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
if(diffInDate == 6) {
diff = diff + 7
modifiedDate.setDate(diff)
}
console.log("Given Date : " + orignalDate.toUTCString())
console.log("Modified date for Monday : " + modifiedDate)
}
getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year
Extending answer from #Christian C. Salvadó and information from #Ayyash (object is mutable) and #Awi and #Louis Ameline (set hours to 00:00:00)
The function can be like this
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
d.setDate(diff);
d.setHours(0,0,0,0); // set hours to 00:00:00
return d; // object is mutable no need to recreate object
}
getMonday(new Date())
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too

Categories

Resources