According to this answer, Firefox and Chrome accepts the format "YYYY MM DD" while creating a date object.
However, Edge doesn't allow new Date("YYYY MM DD") and wants to be initialized as: new Date("YYYY-MM-DD")
So, should i first check which browser is being used before creating a date object or is there a common pattern by which an date object can be created?
I'm not sure I understant your question because for what I've tried firefox allows you to use new Date("YYYY-MM-DD") and so you could use that and avoid the problem with Edge by using always that, anyway if you're getting an Invalid Date this is my solution by example:
var date;
date = new Date("10 01 01"); //invalid date
if(isNaN(date.getDay())){
date = new Date("2010-01-01")
}
Hope this helps you
As mentioned in the previous answer, new Date("YYYY-MM-DD") should work in Firefox. Test this sample code, for example: http://www.w3schools.com/js/tryit.asp?filename=tryjs_date_string_iso1.
There is a separate issue here related to dates that you may have run into, and that is the aligning of UTC dates with user time zones. This thread has more information about this issue and how to accommodate it: Javascript date object always one day off?
Hope this addresses your concerns!
Related
I bumped into a situation where I'm getting a string indicating only the month and year of a date, and I need to create a Date object out of it. If I pass just the string, e.g. "February 2020" into a Date constructor, I strangely get back the the day of the previous month, i.e. in this case 2020-31-01. Thus, I need to always add 1 day to get the proper month in the Date object.
Here is the code to replicate:
var date_str = "February 2020";
var dt = new Date(date_str)
console.log(dt) // Returns : 2020-01-31T23:00:00.000Z (????)
dt.setDate(dt.getDate() + 1);
console.log(dt) // Returns : 2020-02-01T23:00:00.000Z
Any idea what the logic is behind this rather strange behaviour, or do I miss something here?
Update
Have accepted the first answer as being relevant, thus the main question is solved. However, just to add to the confusion: the code snippet I included runs as described with node. Using EXACTLY the same logic in a Vue.js application return the correct Date. Very strange!
"February 2020" is not a valid input according to the specification thus you should not rely on it to work.
You should convert your input to one that is according to spec and then decide whether you need local time or UTC.
Handling time(zones) is one of the hardest things in JavaScript and I strongly recommend that you do not try to reinvent the wheel here yourself as it is really easy to mess up.
Libraries like momentjs can help you here.
Actually you are passing February 2020 into the date Constructor , and its assumes the
date as 1 February 2020 thus it give the output as its UTC date which may be previous
day depending on your region
Use moment.js library, it will give perfect.
moment("February 2020").format('L')
"02/01/2020"
I am sending two fields from client side date and time.
date will be in the format of YYYY-MM-DD i.e 2016-11-08 and time will be in the format of 05:30 PM or 09:45 AM.
I want to combine these two fields and create new field say added_datetime , this field going to be inserted inside MongoDB, so I want it to be in the form of Mongo Date Object so that I can use it for searching with date.
Tried some random things using moments.js but unable to get what I want.
As mentioned in a similiar question you can create a date object with
var date = new Date(datestring);
The code
var startDate = new Date("1900-1-1 8:20:00 PM");
which the original questioner supplied works in chrome and should also work in node since it's the same js engine. This seems to answer your question.
You can find more on dates in the MDN documentation and MongoDB documentation.
I've got an odd situation going on here. I've got the following JSON being passed to the time line control:
[
{
"UserId": 2,
"ItemId": 3,
"ItemText": null,
"ItemDate": "2014-06-09T18:51:37",
"ItemDateEnd": null,
"OutcomeScore": null
},
...
]
This is a simple of array of items that I pass to the control to render. In Firefox this renders perfectly, no problems whatsoever. However, Every other browser I've tried it on shows the items +1 hour. I've tried it in Opera, Chrome and IE9 and they are all showing the same problem apart from Firefox. The now time displays as expected on all browsers.
Interestingly I'm in GMT summer time at the moment which is +1h ... but why would this selectively effect browsers differently?
Each browser is running exactly the same query and getting exactly the same JSON. I'm very confused and not even sure where to start looking.
I'm running v2.5.0 of the time line. I've tried updating to the latest version and the same thing occured so I rolled back to 2.5.0 to get the solved before working on getting the latest version integrated into the page.
Anyone seen this and have a solution?
First, note that the Timeline of the CHAP Links library does not support strings as Date, you should provided Dates or a timestamp with a Number (note that the successor of the Timeline, vis.js, does support strings as date). Strings as Date work nowadays because most browsers now support creating dates from an ISO date string.
The issue you have is because you provide an ISO Date String without time zone information. Apparently not all browsers have the same default behavior in that case. Enter the following in a JavaScript console in both Firefox and an other browser:
new Date("2014-06-09T18:51:37").toISOString()
// output is ambiguous, time zone information missing
and you will see them adding timezone information in different ways. To prevent these kind of ambiguities, you should provide timezone information yourself. To specify the time in UTC, add a Z to the end of the string:
new Date("2014-06-09T18:51:37Z").toISOString()
// output is unambiguous
Creating Date objects from strings is unreliable, as you have observed. You should manually parse those strings into Date objects, like this:
// assumes date string is in the format "yyyy-MM-ddTHH:mm:ss"
var dateMatch = dataItem.ItemDate.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/);
var year = parseInt(dateMatch[1], 10);
var month = parseInt(dateMatch[2], 10) - 1; // convert to javascript's 0-indexed months
var day = parseInt(dateMatch[3], 10);
var hours = parseInt(dateMatch[4], 10);
var minutes = parseInt(dateMatch[5], 10);
var seconds = parseInt(dateMatch[6], 10);
var date = new Date(year, month, day, hours, minutes, seconds);
I'm using the following code to set the date on a datepicker element to today:
document.getElementById('datas').value = $j.datepicker.formatDate('dd.mm.yy', new Date());
It works well except for a couple of customers for whom the date is set to 1 January 1970 (01.01.1970).
I can not get access to the customers' machines for debugging and for all the machines I have access to, using the same browser version, I get the right answer.
What could be wrong with said customers' computers/browsers that would make the code behave so strange? Could it be new Date() returning an invalid object to the formatDate function?
edit: the customers get the same results regardless of the browser they use.
The page works fine in Chrome, but I have this one minor error in Firefox and a different problem in IE. Assistance with either of these issues is greatly appreciated. Since I've been stumped in the Firefox error the longest, I'll start with that one:
Here's the code: http://truxmapper.appspot.com/sched.html
The date picker selects a date using the format "07-08-2010 23:28". Now, I need to pass this time as a parameter to my servlet, which is expecting the time represented as a long. This is not a problem in Chrome. The Date object accepts a string in the format given above, but when I try to use getTime() on a date instantiated with a string in Firefox, it returns NaN. So what I've done in the on the page I linked to is a little handling asking the user to re-enter the dates if its read as NaN. This obviously isn't even a band-aid solution since even if you re-enter the date its still going to read NaN. I need to know why the Date function wont instantiate using the string you see in the input text field in Firefox.
In IE, for some reason its telling me that sTime is undefined.
That date format is ambiguous. Try it as yyyy-mm-dd instead of mm-dd-yyyy or dd-mm-yyyy.
Try
new Date(Date(dateString)).getTime()
(feels like an ugly workaround...)
Edit: This will produce wrong result.
The date format used in Javascript should be of the form YYYY MM DD HH:mm:ss. You can convert the format into this form with
// dateString = "07-08-2010 23:28";
dateString = dateString.replace(/(\d+) (\d+) (\d+)/, '$3-$1-$2');
But as mentioned in the comment, there is no standard Date format used by Javascript before the ECMAScript 5 standard. It is better to parse the dateString directly:
m = dateString.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/)
date = new Date(+m[3], m[1]-1, +m[2], +m[4], +m[5]); // Note: January = 0.