Unexpected results parsing date strings in JavaScript - javascript

I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013

You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp

31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."

If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.

Related

Understanding Date in javascript when a string of numbers is passed to the Date object

Why when a string of numbers of different length is passed to Date in Javascript sometimes returns a Date Object and sometimes Invalid Date.
For example :
new Date('123456') -> Tue Jan 01 123456 00:00:00 GMT+0530
new Date('1234567') -> Invalid Date
new Date('999999') -> Invalid Date
The way you are using the date constructor, the string is interpreted as the year. However, as Xotic750 already stated, dates in Javascript can only be in a range of -100,000,000 days to 100,000,000 days relative to 01 Jan, 1970 UTC. That means '123456' is in the range, but '1234567' and '999999' are not.
Note that using the Date constructor with a string is strongly discouraged because of inconsistency between browsers. It would be better to parse the date yourself and use the constructor taking years, months etc.

moment.js uses the month as day instead the day

I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the .format() method of moment.js I got an incorrect date.
I want to format this datetime string:
from ' 08.10.2016 11:00 ' to ' 08.10.2016 '
Here is a snipped that I used in my angular project:
var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)
If I run this I got this output
10.08.2016
instead of
08.10.2016
The funny thing is, if I want to get the timestamp (milliseconds) of my datetime string, it works perfect. Example:
var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
console.log(dateStart)
Will return
1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200
How can I get the correct Date?
It depends on your locale. en-US locate means moment will parse by "month day year". So, you need to parse with the pattern as well:
var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')

Javascript date object automatically add one day when creating from date string

In my javascript i want to convert date from date string.
i have string like
date = "Thu Sep 03 2015 19:30:00 GMT+0000"
Now i convert string using Date object.
var d = new Date(date);
But this gives me,
Fri Sep 04 2015 01:00:00 GMT+0530 (IST)
It automatically add one day into day. What is wrong?
It automatically add one day into day. What is wrong?
Nothing. The time you input is 19:30 GMT and the timezone on the device you're using is set to GMT+0530. Add 5 hours 30 minutes to 7:30pm and you get 01:00am the following day.
You should not use the Date constructor to parse strings, as it is inconsistent across browsers and until recently, entirely implementation dependent. Manually parse strings, or use a Date library.

JavaScript convert date to format

I'm trying to truncate a JavaScript Date object string from:
Wed Aug 01 2012 06:00:00 GMT-0700 (Pacific Daylight Time)
to
Wed Aug 01 2012
(I'm not particular, could be of format MM/DD/YYYY for example, as long as I get rid of the time/timezone)
Essentially I just want to get rid of the time and the timezone because I need to do a === comparison with another date (that doesn't include the time or timezone)
I've tried using this http://www.mattkruse.com/javascript/date/index.html but it was to no avail. Does anyone know how I can format the existing string such as to get rid of the time? I would prefer to stay away from substring functions, but if that's the only option then I guess I'll have to settle.
Edit: I'm open to options that will compare two date objects/strings and return true if the date is the same and the time is different.
The only way to get a specific format of date across different browsers is to create it yourself. The Date methods in ECMAScript are all implementation dependent.
If you have a date object, then:
// For format Wed Aug 01 2012
function formatDate(obj) {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
return days[obj.getDay()] + ' ' + months[obj.getMonth()] +
' ' + obj.getDate() + ' ' + obj.getFullYear();
}
Though a more widely used format is Wed 01 Aug 2012
Use the Date object's toDateString() method instead of its toString() method.
SIDE BY SIDE DEMO
Even so, it might be better to compare the two date objects directly:
Compare two dates with JavaScript

Javascript convert "05/27 11:00pm" to date?

How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.

Categories

Resources