Javascript - unexpected behavior in dates calculations
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
unexpected javascript date behavior
.getMonth()
is zero-based. as in 0=January
and 11=December
try
var month=newDate.getMonth() + 1;
Javascript setDate() unexpected behaviour wrong month
setDate()
and getDate()
functions only refer to the day of the month. When you subtract 10 days from the d
object it automatically sets the month too, so as July. But, when you set the date of defaultDate
object, you only set the days(so the Month and day of week is not changed).
unexpected behavior in moment js when converting string to datetime in nodejs
As the documentation states:
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use
moment.utc() instead of moment().
so one possible approach would be to work in UTC and do:
const myDate2 = moment.utc('03/08/2017 01:00:01', ['DD/MM/YYYY hh:mm:ss'], true).toDate();
console.log(myDate2.getUTCDate());
console.log(myDate2.getUTCMonth() + 1);
console.log(myDate2.getUTCHours());
Note that in order to get the day number, one has to call getUTCDate
, the getUTCDay/getDay
returns the day of the week instead. Also, the month number returned by getMonth/getUTCMonth
is in the range 0-11
so one has to increment the result by one.
Alternatively, one can work in local date and do:
const myDate1 = moment('03/08/2017 01:00:01', ['DD/MM/YYYY hh:mm:ss'], true).toDate();
console.log(myDate1.getDate());
console.log(myDate1.getMonth() + 1);
console.log(myDate1.getHours());
momentJs parse Date: Unexpected behaviour
A few things:
Do not pay attention to the
_d
field. Underscored fields are internal to moment's API, and may not always be what you expect. In many functions, it has to be evaluated in combination with other internal fields (such as_offset
) in order to produce a valid output. Instead, use the various public functions, such asformat
,toDate
,.valueOf
, and others.Recognize there are many difference between how the
Date
constructor parses strings and how moment's parsing functions work. Don't expect them to match.When a string doesn't contain any time zone information,
moment(...)
will always treat it as local, whilemoment.utc(...)
will treat it as UTC. (Your answer gives a good example of that.)When the
Date
constructor is given a string, the format of the string can affect the interpretation significantly. The actual behavior can vary across implementations, but most current browsers will see the hyphens and theT
as an indication that the string is in ISO8601 format. However without any trailingZ
or offset, the ES5 spec says to interpret those as UTC. This has changed for ES6, which will treat those cases as local time - to better conform with the ISO8601 spec. Since it's not clear when various environments will start to implement this change, it's prudent to not rely on theDate
constructor.If you wanted the
Date
constructor to interpret your value as local time (with ES5), one approach is to use string replacements to remove theT
and swap the hyphens (-
) with slashes (/
). This works in the majority of environments, though there is no specification around this. (I've been told it fails in some Safari browsers.) Really, I would just use Moment's parsing functions, and not rely on theDate
constructor at all.
Similar Date Format produces unexpected date Javascript
The reason why you are seeing this is actually described on the Date.parse()
page of MDN (where a lot of the details around officially-supported Date
parameter formats are described). Specifically:
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore Date objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.
So what you're seeing is a combination of two things:
- The constructor is reading your properly-formatted ISO date value as UTC, since no time zone is provided, and
- It is accurately identifying that your local computer timezone is U.S. Eastern, and adjusting the value appropriately.
As a result, you are seeing the U.S. Eastern Time zone version of midnight on January 1st, 2000, UTC time (or, 7 PM on December 31st, 1999).
Since your first example is using a non-standard format (from JS's point-of-view), the first assumption is not coming into play and the value is being created assuming the local timezone for the value (a browser-specific decision on how to handle a non-standard format).
JavaScript: unexpected result getting number of days remaining in the month
I believe I just stumbled on the answer - when specifying a date months are counted from 0 to 11, but days are still counted from 1 to 31. Therefore, specifying
Date(d.getFullYear(), d.getMonth() + 1, 0);
is basically shorthand for the last day of the current month. The next line is then redundant:
nxt.setDate(nxt.getDate() - 1);
This will give an incorrect result, as it basically decrements a second time. The problem is not with UTC/nonUTC, but rather incorrect day specification. Not sure if this shorthand could cause other problems further down the line though.
Related Topics
How to Sequentially Run Promises with Q in JavaScript
How to Avoid Long Nesting of Asynchronous Functions in Node.Js
Highlight Text Range Using JavaScript
Does JavaScript Support 64-Bit Integers
React Router with Optional Path Parameter
Javascript: Get Code to Run Every Minute
Is It Ok to Add Your Own Attributes to HTML Elements
Counting and Limiting Words in a Textarea
Jquery Change Event on an <Input> Element - Any Way to Retain Previous Value
How to Find a User's Country Using HTML5 Geolocation
What Does Three Dots Do in Reactjs
JavaScript Seconds to Minutes and Seconds
What's the Fastest Way to Convert String to Number in JavaScript
What the Difference of This.State and This.Setstate in Reactjs
How to Stop a Requestanimationframe Recursion/Loop
Using Queryselectorall to Change the Style Property of Multiple Elements