Moment Js Issue : isoWeekYear & isoWeek method behavior - javascript

I fetched the iso week from a date by using moment's isoWeek function.
moment(new Date(2015,11,28)).isoWeek() //output 53
I fetched the iso week year from the same date by using moment's isoWeekYear function.
moment(new Date(2015,11,28)).isoWeekYear() //output 2015
But when I gave the same outputs to the input of moment function it results a different date.
moment().isoWeek(53).isoWeekYear(2015).isoWeekday(0).toDate() //output Dec 28 2014
For other dates it is working correctly. Is there anything that I am missing in my code or it is a bug with Moment ?
here is a demo JSFiddle console.log("Iso Week :",moment(new Date(2015,11,28)).isoWeek());
console.log("Iso Year :",moment(new Date(2015,11,28)).isoWeekYear());
console.log("Date :", moment().isoWeek(53).isoWeekYear(2015).isoWeekday(0).toDate());

It might be the order you've given to the segments.
This works:
moment().isoWeekYear(2015).isoWeekday(1).isoWeek(53).toDate());
Check this out from Moment.js docs.
if you chain multiple actions to construct a date, you should start
from a year, then a month, then a day etc. Otherwise you may get
unexpected results, like when day=31 and current month has only 30
days (the same applies to native JavaScript Date manipulation), the
returned date will be 1st of the following month.
Also isoWeekDays go from 1 to 7. By setting 0 you were getting next week's Monday.

first you have to understand one thing.in your first operation whats happening here is,
moment(new Date(2015,11,28)).isoWeek() //output 53
while creating date using new Date() you have passed 11 as month.so what will happen is while creating date month will get incremented by 1.so the date will be 2015-12-28.so the week number is 53.
so for the 3rd operation you have passed the same result.so moment returned the correct date.
in your case if you want to pass month subtract that by 1 in your 1st operation.
moment(new Date(2015,10,28)).isoWeek();
now you will get the correct answer

Related

Inconsistency when converting DateTime to JavaScript

I have a ASP.NET webapi with a DateTimeZoneHandling set to Local and I am getting two different results when converting to a JavaScript date.
Example 1
Date returned from server 1932-10-13T00:00:00-04:00
var strDate = new Date("1932-10-13T00:00:00-04:00");
strDate.toISOString(); // 1932-10-13T04:00:00.000Z
strDate.toLocaleString(); // 10/12/1932, 11:00:00 PM
Example 2
Date returned from server 2013-05-09T00:00:00-04:00
var strDate = new Date("2013-05-09T00:00:00-04:00");
strDate.toISOString(); // 2013-05-09T04:00:00.000Z
strDate.toLocaleString(); // 5/9/2013, 12:00:00 AM
I expected behaviour should always be midnight as the dates returned from the server are always midnight. It appears all recent dates parse correctly, however, dates far in the past are incorrect.
The timezone can vary in some locales, for example, I'm UTC-0300, and on certain season shifts it becomes UTC-0200, so it indicates that your locale changed the offset too, making it display the time one hour lesser, basicaly because you locale adopted a different offset along the year.
The example bellow, I've changed your first example to use the same day and month than the second one, so that it proves you that old dates has nothing to do with it.
console.log("Example One");
var strDate = new Date("1932-05-09T00:00:00-04:00");
console.log(strDate.toISOString());
console.log(strDate.toLocaleString());
console.log("--------------------------");
console.log("Example Two");
var strDate2 = new Date("2013-05-09T00:00:00-04:00");
console.log(strDate2.toISOString());
console.log(strDate2.toLocaleString());
Further explanation on UTC/Zulu time
It has normalized the iso date to a zulu date (zero offset iso date). It is still the same datetime, but it has converted the timezone offset into hours making the timezone offset zero.
date [2013-05-09]
separator [T]
time [00:00:00]
offset [-04:00]
The fundamental aspect is that 00:00:00.000-04:00 is the same than 04:00:00.000Z.
If you're simply trying to display the date as someone living in that time would have remembered it (in your case, October 13th happened on October 13th), you may be able to (ab)use Moment Timezone, which appears to format the date as expected:
moment.tz("1932-10-13T00:00:00-04:00", "America/Toronto").tz("UTC").format(); // 1932-10-13T04:00:00Z
In your case, this hacktechnique results in 1932-10-13T04:00:00Z which may be what you are looking for.

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/

Error setting date of month to 31st

While setting the date to 31st we encountered this issue.
function getTodayMidnight() {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(1);
date.setMilliseconds(0);
return date;
}
function getDates() {
var octStartDate = getTodayMidnight();
octStartDate.setDate(1);
octStartDate.setMonth(9);
var octEndDate = getTodayMidnight();
octEndDate.setDate(31);
octEndDate.setMonth(9);
console.log(octStartDate);
console.log(octEndDate);
}
getDates();
I'm accounting for the date offset in my timezone (+530, 330 mins). For start of the month case, the behaviour is expected. (We expect to go back to the previous month and display the date). But we are getting an erroneous output in the case of the last date of the month. Why are they pointing to the same date?
Assuming you ran this program today (15th November), then new Date() returns a Date object with the month set to November. So a call to setDate(31) will result in the date overflowing to 1st December (because November only has 30 days). You then call setMonth(9), so the final result corresponds to 1st October.
Obviously, you can avoid this by switching the order of your method calls.
But to avoid this ordering problem entirely, I'd suggest using the Date(year, month, date, ...) constructor (this also avoids mutating a value type, which is generally considered to be a good thing).

Comparing 2 dates with momentJS

I am trying to compare a DAY/TIME e.g. Monday 09:00:00 with the current time to see if I am past that point in the week. e.g. If it is now 05:00:00 on Monday it should return true however it is returning false everytime
var dayTime = Moment("Wednesday 17:00:00", "dddd HH:mm:ss");
var now = Moment(Moment.now(), "dddd HH:mm:ss");
console.log(Moment.utc(dayTime).isBefore(now)); //returns false all the time
I found the following similar questions but it didn't seem to fix the issue after formatting the time.
Comparing two times with Moment JS
When I replace the moment.now() with a string such as "Wednesday 17:00:00" it returns the expected result.
Any idea what I need to do to moment.now() in order for this to work correctly?
Moment.now can be used as an extension point, but it's really not a public API. To get the current time in momentjs you just call moment(). Note that all moment calls use lowercase moment.
To see if your date and time is before the current time, you would just call:
moment('01/01/2016', 'MM/DD/YYYY').isBefore(moment())
You would replace the date and format in question with your own.
I see that you have a date format that includes only day of week and time. Moment will parse this, but be aware that the behavior might not be what you expect. When I parse your date, I get Wednesday December 30, 2015. Exactly what day this lands on will vary by locale. In any case, I doubt that it is what you want. If at all possible, I would get year, month, and day.
If you would like to instead set the moment to Wednesday this week, set the day on the moment using .day(). For instance:
moment().day(3).format()
"2016-06-15T20:19:55-05:00"
For anyone who is interested, the code I posted in my question was changing the day/hour but was setting the year to 2015 which meant that it was always in the past.
To fix I separated out the Day and the Hour and set to moment. Then compared that with now. e.g.
moment().set({"Day": "Friday", "Hour": "17"}).isBefore(moment())

Javascript returns wrong Date values (NodeJS)

I'm working on a NodeJS Projects and I get wrong Date values. And I don't get what I am doing wrong.
var d = new Date(results[1].timestamp);
console.log(results[1].timestamp); // 2016-05-10T13:29:47 <- this is right (stored at my DataBase)
console.log(d.getDate()); //10
console.log(d.getFullYear()); //2016
console.log(d.getMonth()); //4
console.log(d.getDay()); //2
console.log(d.getHours()); //15
console.log(d.getMinutes()); //29
console.log(d.getSeconds()); //47
So Month, Day and Hours are wrong.
I see these results in google chrome at my Mac
Thanks for helping
A few errors here:
getMonth returns a 0 based month. That is May is 04.
getDay returns the day of the week. I guess you want getDate
the date is parsed as UTC and getHour is according to the locale. So the hour might be different from what you want (but right here it seems to be "exact", as is it's the same value than inputted).
A tip for your next problems: Have a look at some documentation. For example the MDN.
The getDay() method returns the day of the week (from 0 to 6) for the specified date.
The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.
The getHours() method returns the hour (from 0 to 23) of the specified date and time.
getDay() function returns the Day of the date i.e. from sunday to saturday(0 to 6)
getMonth() function returns month frome January to December (0 to 1) so here you need to add 1 to correctly get the value
and I am afraid you misinterpreted getHours() result, because if I check for the mentioned date it gives me 13

Categories