Javascript milliseconds notaion was not working in firefox - javascript

Can anyone help me with this ?
var current_date=new Date('2012/12/21 22:59:59.997');
var result=current_date.getTime();
Im not getting result in Firefox but it does show in chrome, in FF it shows invalid date.

You should be able to do the following (using date.setMilliseconds):
var dateString = '2012/12/21 22:59:59.997';
var dateStringSplit = dateString.split('.');
var myDate = new Date(dateStringSplit[0]);
myDate.setMilliseconds(dateStringSplit[1]);
console.log(myDate);

Firefox and some other browsers (namely, Safari or Opera) don't like milliseconds.
// Split off the part after the dot
var current_date = new Date('2012/12/21 22:59:59.997'.split('.')[0]);
// Works everywhere!
var result = current_date.getTime();
If you really want to work with milliseconds, you have to split the date in multiple parts and use new Date() with those. From MDN documentation, here are the options:
new Date(year, month, day [, hour, minute, second, millisecond])
Or, as h2ooooooo says, you can use the second part of the split date and use setMilliseconds.
Overall, you have plenty of solutions. Choose the one that annoys you the least.

The format you are using is not a standard format for Date.parse
You may want to split the string and set the parts individually. Also, please manage the time zone correctly as it is not apparent which timezone the date string is in.

Related

javascript: IE alternative to convert ISO to local time

I am trying to convert ISO time local time.
here is my code :
var local_date = new Date('2018-09-11T06:22:39.000-0400');
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
this code is working fine in chrome but in IE its giving error.
first line of code gives me Invalid Date
Looking for a fix which works in all browsers.
FYI: I do not want to use moment.js or any other library, want it in vanilla javascript.
So, the problem is your date-string format.
By reading the Mozilla documentation about the Date Object we can see that your string has to follow the IETF-compliant RFC 2822 timestamps and the ISO8601.
If we open the second one (the ISO8601) we can see that the accepted format is YYYY-MM-DDTHH:mm:ss.sssZ where the Z may be (+|-)HH:mm.
So instead of new Date('2018-09-11T06:22:39.000-0400'); if we execute new Date('2018-09-11T06:22:39.000-04:00'); it works.
If you don't want to add it manually, you can do it automatically by using the splice method from this answer and the code:
// A nice Polyfill
if (!String.prototype.splice) {
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
// Your code
var dateString = '2018-09-11T06:22:39.000-0400'.splice(26, 0, ":");
var local_date = new Date(dateString);
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
I don't claim that 2018-09-11T06:22:39.000-0400 is in an invalid format, but an unaccepted by the IE.
Also, if you want to vanilla javascript you should stop opening IE at all.

adding minutes to a date (javascript) invalid date

I've this function to add minutes to a date in javascript
function addMinutes(date, minutes) {
var DateObject = new Date(date);
var modifiedDate = DateObject.getTime() + minutes * 60000;
return date = modifiedDate;
}
The script works perfectly on most of my pages but on the current page i'm working on I've this date: 2014-06-07 01:00:00
This works only in google chrome.. I've that browsers like IE/Safari are not able to work with YYYY/MM/DD format.
I've tried to parse it with Date, but this is kinda new for me and I'm not sure what i'm doing wrong.
here's a fixed copy of the orig with suggestions implemented:
function addMinutes(date, minutes) {
var DateObject = new Date(String(date).replace(/\ /g,"T")+"Z"),
modifiedDate = DateObject.getTime() +
(minutes* 60000) +
(new Date(DateObject).getTimezoneOffset()*60*1000) ;
return date = modifiedDate;
}
new Date(addMinutes("2014-06-07 01:00:00", 15)).toLocaleString();
// shows: "6/7/2014 1:15:00 AM"
There are two different problems here that you should mentally separate:
Parsing a string in the particular format of YYYY-MM-DD hh:mm:ss to a Date object.
Adding minutes to a Date object.
Parsing the String
You should be aware that the parsing behavior when you pass a string to the Date constructor is implementation specific, and the implementations vary between browser vendors.
In general, when dashes (-) are present, the values are treated as UTC, and when slashes (-) are present, the values are treated as local to the time zone where the code is running.
However, this only applies when either a time is not present, or when the date and time components are separated with a T instead of with a space. (YYYY-MM-DDThh:mm:ss)
When a space is used to separate date and time components, some browsers (like Chrome) will treat it as local time, but other browsers (like IE and Firefox) will consider it an invalid date.
Replacing the space with a T will allow the date to be parsed, but if that's all you do, then Chrome will treat it as UTC, while IE and Firefox will treat it as local time.
If you also add the trailing Z, (YYYY-MM-DDThh:mm:ssZ) then all browsers will parse it as UTC.
If you want a format that all browsers will recognize as local time, there is only one, and it's not ISO standard: YYYY/MM/DD hh:mm:ss. Thus, you might consider:
var s = "2014-06-07 01:00:00";
var dt = new Date(s.replace(/-/g,'/'));
Adding Minutes
This is much more straightforward:
dt.setMinutes(dt.getMinutes() + 15);
That will simply mutate the Date value to add 15 minutes. Don't worry about overflow - if getMinutes returns 55, setting 70 minutes will properly add 1 hour and 10 minutes.
A Better Solution
Moment.js removes all of the guesswork about parsing variations, and gives you a much cleaner API. Consider:
// parse a string using a specific format
var m = moment("2014-06-07 01:00:00","YYYY-MM-DD HH:mm:ss");
// adding time
m.add(15, 'minutes');
// format the output as desired, with lots of options
var s = m.format("L h:mm:ss A");

What is needed for a valid Javascript Date object?

I've been banging my head over this one all day. No matter how I initialize a Javascript Date I cannot seem to get a valid Date object... I'm assuming the Date is invalid and not working properly by inspecting it with Chrome's debugger, which has the value '__proto__: Invalid Date'.
I've tried all of the following:
var d = new Date();
var d = new Date('2012-10-08');
var d = new Date('2012-10-08 00:00:00');
var d = new Date(Date('2012-10-08'));
var d = new Date(Date.parse('2012-10-08'));
var d = new Date(2012,10,08);
var d = new Date("October 13, 1975 11:13:00");
Along with countless other attempts.
This is presenting a problem in iOS where I'm trying to get values from these Date objects but every function just returns NaN. I'd prefer to avoid having to use external libraries or have to convert YYYY-MM-DD format into any other format since I'm trying to get this to work with an HTML5 input type="date" with minimal code for a mobile site.
Essentially this boils down to: What are the parameters that make a Date object valid?!
Do not trust the Date object to parse strings, you must do it manually. Given the format 2012-10-08,
function stringToDate(s) {
s = s.match(/\d+/g);
if (s) {
return new Date(s[0], --s[1], s[2]);
}
}
You may want to do some validation of the input string and the resulting date object, the above just shows the conversion.
Edit
BTW, the only string format that seems to be parsed consistently in all browsers is the US-specific month/date/year format. There is no specification to support its use, nor is there any reason to believe browsers will continue to support it other than pragmatism and "legacy" reasons.
For the vast majority of regions, '2/3/2012' is interpreted as 2 March, so getting 3 February might be unexpected.
Once older versions of IE are no longer in use (probably a few years yet), it should be safe to use the ISO8601 extended format per ECMA-262. However, even browsers that support it are inconsitent. e.g given:
new Date('2011-02-29');
Firefox 15 returns 'Invalid Date', IE 9 and Chrome 22 return a date object for 1 March, 2011.
There are three ways of calling the method:
The number of milliseconds from the epoch:
new Date(milliseconds)
Any IETF-compliant RFC 2822 timestamp:
new Date("November 2, 1988 10:00:00");
Individual args:
new Date(year, month, day [, hour, minute, second, millisecond])
new Date(1988,11,02,10,0,0);
If your main concern is about parsing, have a look at Moment.js which is clearly superior to parsing things yourself. (IMHO)
Turns out jQuery doesn't bind the .change() event to input type="date" properly in iOS. Changed the event to .blur() and everything seems to work now. However, it still seems it is impossible to create a valid date object in Chrome... an issue for another day.
Thanks for the help everyone!

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

javascript : how to get 'utc date'

I have a date in this string format "02/28/2012" and I want to convert it to UTC.
I'm using the jquery datepicker to select thedate and populate an inputbox. any clues?
Thanks
var datestr = "07/08/2005";
var datearr = datestr.split("/")
var utc = Date.UTC(datearr[2],datearr[0],datearr[1]);
var utcdate = Date.UTC(2012,2,28);
The other answers are good, but they will give you the wrong result.
In Javascript, the month argument is zero-indexed, so make sure to subtract 1 from the standard month number,
var utcms = Date.UTC(2012,2-1,28);
Unfortunately jquery .datepicker.parseDate(str) injects a local timezone (it would be nice if the documentation said this), and Date(str) and Date.parse(str) appear unpredictable about their treatment of local vs UTC.

Categories

Resources