How to get start and end of day in Javascript? - javascript

How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )? Computer use a local time.

var start = new Date();
start.setUTCHours(0,0,0,0);
var end = new Date();
end.setUTCHours(23,59,59,999);
alert( start.toUTCString() + ':' + end.toUTCString() );
If you need to get the UTC time from those, you can use UTC().

With dayjs library, use startOf and endOf methods as follows:
Local GMT:
const start = dayjs().startOf('day'); // set to 12:00 am today
const end = dayjs().endOf('day'); // set to 23:59 pm today
For UTC:
const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
const start = dayjs.utc().startOf('day');
const end = dayjs.utc().endOf('day');
Using the (deprecated) momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today
For UTC:
var start = moment.utc().startOf('day');
var end = moment.utc().endOf('day');

Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter
var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
remove .toUTC() if you need only the local time
and you may ask why not moment.js, answer is here for that.

FYI (merged version of Tvanfosson)
it will return actual date => date when you are calling function
export const today = {
iso: {
start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
now: () => new Date().toISOString(),
end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
},
local: {
start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
}
}
// how to use
today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" *
* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)

In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');

One liner - considering local timezone and without libraries
const todayStart = new Date(new Date().setHours(0, 0, 0, 0))
const todayEnd = new Date(new Date().setHours(23, 59, 59, 999))
const tomorrowStart = new Date(new Date(new Date().setHours(0, 0, 0, 0)).setDate(new Date().getDate() + 1))
const tomorrowEnd = new Date(new Date(new Date().setHours(23, 59, 59, 999)).setDate(new Date().getDate() + 1))
const monthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1).setHours(0, 0, 0, 0))
const monthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).setHours(23, 59, 59, 999))
const nextMonthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).setHours(0, 0, 0, 0))
const nextMonthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).setHours(23, 59, 59, 999))
console.log({
todayStart,
todayEnd,
tomorrowStart,
tomorrowEnd,
monthStart,
monthEnd,
nextMonthStart,
nextMonthEnd,
})

If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60, 12 hours: 1000 * 60 * 60 * 12, etc.)
const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds
let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999

I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:
var startOfDay = dateFns.startOfDay;
var endOfDay = dateFns.endOfDay;
console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>

We can use moment for this.
// for day start time
moment(moment().startOf('day')).format('HH:mm')
// for day end time
moment(moment().endOf('day')).format('HH:mm')

As you are interested in the UTC start/end of day, you can also use the modulo operator:
const now = new Date().getTime();
let startOfDay = now - (now % 86400000);
let endDate = startOfDay + 86400000;
where 86400 is the number of seconds of one day and the resulting variables are the Epoch in milliseconds.
If you prefer Date Objects:
const now = new Date().getTime();
let startOfDay = new Date(now - (now % 86400000));
let endDate = new Date(now - (now % 86400000) + 86400000);

Based on the most rated answer, but to define the dates in just one line:
const startToday = new Date(new Date().setUTCHours(0,0,0,0));
const endToday = new Date(new Date().setUTCHours(23,59,59,999));
Explanation:
new Date().setUTCHours(0,0,0,0) // returns the epoch time number
new Date(/* epoch number */) // returns that epoch Date object
that is why both new Date constructors are needed.

It might be a little tricky, but you can make use of Intl.DateTimeFormat.
The snippet bellow can help you convert any date with any timezone to its begining/end time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

// get current time for UTC timezone
const d = new Date();
const year = d.getUTCFullYear();
const month = d.getUTCMonth();
const day = d.getUTCDate();
// set time to begin day UTC
const startTime = Date.UTC(year, month, day, 0, 0, 0, 0);
//set time to end day UTC
const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);

Related

Display year to date

I am trying to display data for a "Year to Date" range. I need it to show all the dates ranging from the first day of January 2021 until the current date (whatever day today is).
I previously had the data showing only the previous 30 days and had:
const today = new Date();
const startDate =
this.startDate || new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
const endDate = this.endDate || today;
How can I get the data to show from January 1st, 2021 to whatever the current day is?
Here is how to create an array dateArray of all dates between the first of this year and today:
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
const today = new Date()
const startDate = new Date(today.getFullYear(), 0, 1);
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= today) {
dateArray.push(new Date(currentDate));
currentDate = currentDate.addDays(1);
}
console.log(dateArray)
This will work for every current year
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const dates = [...Array(days)] // create an array of days
.map(() => new Date(t+=aDay).toISOString().split('T')[0])
console.log(dates)
Using while
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const endTime = end.getTime();
const dates = [];
while (t<endTime) {
dates.push(new Date(t+=aDay).toISOString().split('T')[0])
}
console.log(dates)
As others have answered, just "better" — IMHO of course. :-)
// Default end is current date
function getDateRange(startDate, endDate = new Date()) {
// Default start to 1 Jan of endDate year
if (!startDate) {
startDate = new Date(endDate.getFullYear(), 0);
// Otherwise copy startDate so don't affect original
} else {
startDate = new Date(+startDate);
}
let result = [];
// Push timestamps into an array until endDate
while (startDate <= endDate) {
// Push date in YYYY-MM-DD format into result array
result.push(startDate.toLocaleDateString('en-CA'));
// Increment startDate
startDate.setDate(startDate.getDate() + 1);
}
return result;
}
// Dates from 1 Jan to today
console.log(getDateRange());

How do I convert this date from momentjs to plain JavaScript

I have a timestamp that I am trying to roundto the nearest UTC Monday 00:00:00:00:000Z
My code in moment looks like this
let now = Date.now()
moment.unix(now / 1000).utc().startOf("isoWeek").valueOf()
I am trying to do this in plain JS without moment and I am not getting the same answer
const nearestMonday = date => {
const monday = 1;
const currentDay = date.getDay();
const distance = (monday + 7 - currentDay) % 7;
const newDate = new Date(date.getTime());
newDate.setDate(date.getDate() + distance);
newDate.setHours(0, 0, 0, 0);
return newDate;
}
> d = Date.now()
1545989455067
> nearestMonday(new Date(d)).getTime()
1546194600000
> m.unix(Date.now() / 1000).utc().startOf("isoWeek").valueOf()
1545609600000
I am in GMT + 530 zone , what do I change to get the same answer as moment
Ok, so we have a few problems here:
First: Timezones
Date works with your local timezone, so when you do newDate.setHours(0, 0, 0, 0); and stuff like that, it sets the object to that hours in your timezone. When you do .getTime(), however, it does return millis from epoch in UTC.
The result of this being: if you are in gmt+530 (India, I believe) when you do a .getTime() the millis from epoch will be off by that difference (5h 30m).
To compensate that, you can use getTimezoneOffset():
const nearestMonday = date => {
const monday = 1;
const currentDay = date.getDay();
const distance = (monday + 7 - currentDay) % 7;
const newDate = new Date(date.getTime());
newDate.setDate(date.getDate() + distance);
newDate.setHours(0, 0, 0, 0);
newDate.setTime(newDate.getTime()-1000*60*newDate.getTimezoneOffset());
return newDate;
}
On the other hand, your code using moment will work properly with timezones, so there's no need to change it.
Second: What monday?
Your function nearestMonday calculates the next Monday.
The function startOf('isoWeek') sets the date to the Monday of the current week.
If you want both to calculate the current, you should modify your nearestMonday like:
const nearestMonday = date => {
const monday = 1;
const currentDay = date.getDay();
const distance = monday - currentDay;
console.log('dist', distance);
const newDate = new Date(date.getTime());
newDate.setDate(date.getDate() + distance);
newDate.setHours(0, 0, 0, 0);
newDate.setTime(newDate.getTime()-1000*60*newDate.getTimezoneOffset());
return newDate;
}
Last: Sundays?
getDay() on Sunday will return a 0. Therefore, the "nearestMonday" will be the day after that. I haven't corrected it since I don't know if that's the desired behaviour, but noting it just for completion sake
I think this may do what you want:
const nearestMonday = date => {
const day = 1000*60*60*24;
const week = day*7;
return new Date(Math.floor(date.getTime()/week)*week-3*day);
}

Increment date by one day to a set epoch date

I would like to increment a (epoch) date by one day.
So far I have:
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
This spits out 25 so I am on the right track. How would I convert it back to a Date object?
This is going to be in this map function:
return data.map(t => ({
id: t.id,
start_date: new Date(parseInt(t.date_created, 10)),
duration: // here, taking the above start date and adding one day
)
}));
I think you can add day in milliseconds to achieve this.
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
let nextDay = +date + (24 * 60 * 60 * 1000) // 1 day in millisecond
nextDay = new Date(nextDay)
console.log(nextDay)
You can also use momentjs in following way:
var date = 1535162451650
date = moment(abc)
console.log('date', date.format('DD MM YYYY'))
date = date.add(1, 'day')
console.log('date', date.format('DD MM YYYY'))
How about this?
var options = {
id: t.id,
start_date: new Date(parseInt(t.date_created, 10))
};
options.duration = new Date(options.start_date.getTime());
options.duration.setDate(options.duration.getDate() + 1);
return data.map(t => (options));
I think I figured it out. Looks ugly but seems to work
let date = "1535162451650";
console.log(new Date (new Date(parseInt(date, 10)).setDate(new Date(parseInt(date, 10)).getDate() + 1)));
// gives me aug 25 2018
Is there a cleaner way to do this? haha

datetime to timestamp javascript

i have this time format :
DateTime(2015, 5, 11, 12, 0, 0)
i would like to know if i can convert it into a time stamp.
i have made this convert function from ISO 8601 to Timestamp and i would like to know if i can adapt it to this time format :
var myDate = new Date("2017-07-31T15:30:00+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(myDate.getTimezoneOffset()*60 * 1000)
console.log('with Offset ' + withOffset);
console.log('without Offset (timeStamp of your timezone) ' +withoutOffset);
did you try
Date.parse(your date here)/1000
Date.parse(new Date(2015, 5, 11, 12, 0, 0))/1000
you can use the library momentjs to convert it.
Here you are assigning an instance of momentjs to CurrentDate:
var CurrentDate = moment();
Here just a string, the result from default formatting of a momentjs instance:
var CurrentDate = moment().format();
And here the number of seconds since january of... well, unix timestamp:
var CurrentDate = moment().unix();
momentjs guide
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

Find out how many days till next birthday and previous birthday - javascript [duplicate]

I tried this but it fails
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.
The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,3,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Why reinvent the wheel??
Use datejs
and after:
var startd = Date.parseExact(ind, "yyyy-MM-dd");
var endd = Date.parseExact(end, "yyyy-MM-dd");
var diff = new Date(endd - startd);
var days = diff/1000/60/60/24;
That's all folks!
The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.
The fromNow function is also super nice if want to display the number of days from now you could do something like:
moment([2014, 4, 5]).fromNow();
would produce something like "330 days" if it's 330 days away.
http://momentjs.com/docs/#/displaying/fromnow/
Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):
const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');
Simple, fast, accurate!
Here's the same code, explained:
// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';
// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');
// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');
// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');
If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.
The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.
This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.
const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);
export const daysUntilBirthday = () => {
const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
const oneDay = 24 * 60 * 60 * 1000;
const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
const firstDate = new Date();
const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
const daysOrDay = days === 1 ? 'day' : 'days';
return days !== 365 ? `${days} ${daysOrDay} until my birthday 😉😉` : '🎂 TODAY IS MY BIRTHDAY 🎂';
};

Categories

Resources