Get last date of month of passed date - javascript

I have date like 2022-09-18T18:30:00Z
I want last date of the month
I'm using below snippet
moment(`2022-09-18T18:30:00Z`).clone().endOf('month').utc()
I'm using Node.js and it's working in my local, but not in my live server. It doesn't gives me UTC time instead gave me 2022-09-30 23:59:59

Without moment.js you can just set the UTC date to the last day of the month, e.g.
let d = new Date('2022-09-18T18:30:00Z');
d.setUTCMonth(d.getUTCMonth() + 1, 0);
console.log(d.toISOString()); // 2022-09-30T18:30:00.000Z

Related

Javascript - force new Date constructor to treat argument as UTC

Have an API end point that accepts a date and does some processing. I do give via postman the date as UTC (denoted by the Z at the end). Sample input sent from Postman.
{
"experimentDate":"2022-01-12T12:30:00.677Z",
}
In the code when I do
let startDate = new Date(experimentDate);
//other calculations e.g get midnight of the startDate
startDate.setHours(0,0,0,0);
The first assignment sets startDate corrected to the current timezone. The rest of my calculations go bad as a result of this. For instance when I use the setHours function setting time to 0, I expect it to be at midnight of the UTC time given but it goes to midnight of my current timezone.
Should new Date not keep the date in UTC given that there is a Z at the end of the date?
Should I reconvert it to UTC like below. Is this not redundant?
Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth(),
startDate.getUTCDate(), startDate.getUTCHours(),
startDate.getUTCMinutes(), startDate.getUTCSeconds())
What is the right way to achieve this?
The Date object will be stored as a UTC date, however there are different methods on it that will set/get the date or time for both UTC and local timezones. Try using .setUTCHours(), rather than .setHours().
You can use the Date constructor to parse the timestamp provided.
Most of the methods will treat the date as a local time. For example, the getHours() method returns the hour for the specified date, according to local time.
However you can use the getUTCXXX() methods to get the UTC date components such as year, month, date, hour etc.
You can also use Date.toISOString() to get the date formatted as UTC.
You can use the Date.UTC method to get UTC midnight, passing in the relevant getUTCFullYear(), getUTCMonth(), getUTCDay() etc. from the experiment date.
This can then be passed to the Date constructor.
let timestamp = "2022-01-12T12:30:00.677Z";
const experimentDate = new Date(timestamp);
const midnightUTC = new Date(Date.UTC(experimentDate.getUTCFullYear(), experimentDate.getUTCMonth(), experimentDate.getUTCDate()))
console.log('Experiment date (UTC): ', experimentDate.toISOString());
console.log('Midnight (UTC): ', midnightUTC.toISOString());
You can also use Date.setUTCHours() to do the same thing.
let timestamp = "2022-01-12T12:30:00.677Z";
const experimentDate = new Date(timestamp);
const midnightUTC = new Date(experimentDate);
midnightUTC.setUTCHours(0,0,0,0);
console.log('Experiment date (UTC): ', experimentDate.toISOString());
console.log('Midnight (UTC): ', midnightUTC.toISOString());

offset time zone problem with toIsoString : does not convert well the date object

I'm trying to set a date that take the begin of year 2020 with javascript and convert it to isoString; the problem is that always I got a date like this : like "2019-12-31T23:00:00.000Z" !!
start: Date = new Date(new Date().getFullYear(), 0, 1);
how to set the date with this format : "2020-01-01T23:00:01.000Z"
The date produced by new Date() makes an allowance for the host timezone offset, the toISOString method is UTC so unless the host is set to UTC, there will be a difference equal to the host timezone offset. In the OP that's +01:00.
If you want the start of the year UTC, then you have to first generate a time value as UTC, then use that for the date:
// Get the current UTC year
let year = new Date().getUTCFullYear();
// Create a Date avoiding the local offset
let d = new Date(Date.UTC(year, 0, 1));
// Get a UTC timestamp
console.log(d.toISOString());
If, on the otherhand, you want an ISO 8601 timestamp with the local offset rather than UTC, something like 2020-01-01T00:00:00.000+02:00, you'll have to do that yourself or use a library (per this, thanks to Matt JP), see How to format a JavaScript date.

How to get the start date and end date of a month by passing Month and Year in Moment.js

I am using Moment.js for calendar conversion. Is it possible to get the first and last date of the month by passing month and year.
Month and year format I have is - 10-18 which is in MM-YY format.
I want to get the first and last date of October for instance in 01 Oct 2018.
I can format it the date I want in Moment but was not sure how can I get the first and last date of a month by just passing 10-18.
Any help suggestions would be very helpful.
Thanks
R
Quite easy, just use startOf and endOf ;)
Be careful as it mutates the original moment.
const input = "10-18";
const output = moment(input, "MM-YY");
console.log('Start of the month:', output.startOf('month').format('LL'));
console.log('End of the month:', output.endOf('month').format('LL'));
<script src="https://momentjs.com/downloads/moment.js"></script>
Here is the doc:
https://momentjs.com/docs/#/manipulating/start-of/
https://momentjs.com/docs/#/manipulating/end-of/

javascript dateDate is offset by 1, time zone issue?

I have the following code:
let date = new Date(event.eventDate); //2018-02-12T00:00:00.000Z
date = date.toISOString(); //try random thing here, but not helpful
date = new Date(date.split('T')[0]);
console.log(date, date.getDate()); //output is 11 on my local computer
so 2018-02-12, getDate should be 12, but somehow on my local computer it returns 11.
However, when i run the same code on remote server, it outputs getDate() correctly, which is "12".
how do i make sure the out put is always "12" no matter where i run the code?
Thanks!
getDate is interpretting the date in your local timezone, which is a few hours behind the UTC version of the date, which your server is using. Since the time of the date is midnight, the offset of your local timezone sets it to the prior day. You can replace getDate with getUTCDate to use the UTC value
let date = new Date(event.eventDate); //2018-02-12T00:00:00.000Z
console.log(date.getUTCDate()) // 12
According to MDN:
The getDate() method returns the day of the month for the specified date according to local time.
If you're looking for a fixed (UTC) date that will be the same for each person, you can use getUTCDate():
let date = new Date('2018-02-12T00:00:00.000Z');
date = date.toISOString();
date = new Date(date.split('T')[0]);
console.log(date, date.getDate());
console.log(date, date.getUTCDate());
Hope this helps!

JS: Convert Today's Date to ISOString() with Fixed Time

I'm trying to convert today's date to an ISO standard string but with the fixed time of T00:00:00.000Z.
I can get as far as returning a ISO string of today's date and time:
var isoDate = new Date().toISOString();
// returns "2015-10-27T22:36:19.704Z"
But I wanted to know if it's possible to have a fixed time, so it should return:
"2015-10-27T00:00:00.000Z"
Is this possible?
Any help is appreciated. Thanks in advance!
To get the current UTC date at midnight:
var d = new Date();
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
var output = d.toISOString();
To get the current local date, with the time portion set to UTC midnight:
var d = new Date();
var ts = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
var output = new Date(ts).toISOString();
As for which to use, think through your requirements very carefully, The current UTC date and the local date may indeed be two different days.
For example, when it's midnight (00:00) October 27th in UTC, it's 8:00 PM on October 26th in New York.
Also, consider using moment.js, which makes operations like either of these much easier with the startOf('day') and .utc() functions.

Categories