"Invalid date" error when converting a string to date - javascript

Am trying to convert a string to date
var strdate='2014-04-23+09:06:57.4830591330'
while trying to convert this string to date using below code
var followupDate = new Date(strdate);
console.log(followupDate)
am getting the error
Date {Invalid Date}

You just need a space rather than an addition sign, so you could just replace it:
var strdate='2014-04-23+09:06:57.4830591330';
var followupDate = new Date(strdate.replace("+"," "));
console.log(followupDate);
Will log something like: Wed Apr 23 2014 09:06:57 GMT+0100 (GMT Summer Time).

You should replace the + sign in your string for a space, between the year and the hours.
To explain this, let's see Date documentation :
dateString
String value representing a date. The string should be in a
format recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
Now, from RFC 2822 (under 3.3. Date and Time Specification), it's explicitly described that the + is meant for timezones:
zone = (( "+" / "-" ) 4DIGIT) / obs-zone
Moreover, note that there's no room for milliseconds in this standard.

Your String Format is Wrong
It should be like this
var strdate = "2014-04-23 09:06:57.4830591330"
if you are getting your value dynamicaly then change it to this format by
var newstrdate = strdate.replace("+", " ");
and then try
date = new Date(newstrdate);

Related

How to convert a string into timestamp, with moment js?

I have the string "18/04/19 5:17 PM EDT" which represents a date.
I'm using moment and the add-on moment-timezone and I need to convert this sting into a timestamp.
I'm trying something as:
var date = moment("18/04/19 5:17 PM EDT").format('DD/MM/YY h:m a z');
alert(date);
But this is not working and saying "invalid date".
Please note that moment(String):
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
so you are getting Invalid Date because your input is neither in ISO 8601 nor RFC 2822 recognized format, then you have to provide format parameter when parsing it.
moment(String, String) does not accept 'z' token, so you have to use moment-timezone to parse your input using zone, see Parsing in Zone docs:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
You can use format() and other methods listed in the Displaying section of the docs (e.g. valueOf()) to display the value of a moment object.
Here a live sample:
var date = moment.tz("18/04/19 5:17 PM EDT", 'DD/MM/YY h:m A', 'America/New_York');
console.log(date.valueOf()); // 1555622220000
console.log(date.format()); // 2019-04-18T17:17:00-04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
As a side note, remeber that time zone abbreviations are ambiguous, see here for additional info.

How can I obtain a yyyy-mm-dd HH:mm:ss string from a Date object in pure old JavaScript?

I am not so into JavaScript. I have the following problem trying to format a Date. I can use only plain old JavaScript (no third party library because this script is not performed into the browser but into a Java application using Rhino).
I created my Date object in this way:
d = new Date('2017','11','09','06','00','00');
(into the Rhino environment the Date() constructor works only in this way).
That creates a Date object like this:
Sat Dec 09 2017 06:00:00 GMT+0100 (CET)
Starting from this Date object I want to obtain a String formatted in this way:
yyyy-mm-dd HH:mm:ss
I know that doing:
d.toISOString()
I obtain
2017-12-09T05:00:00.000Z
but it contains the T and Z delimiters.
What is a smart way to do it?
Reformat the ISO string by replace the unnecessary parts with a space, then String#trim the spaces from the end.
Thanks to #zerkms for the regex expression.
var d = new Date('2017','11','09','06','00','00');
var str = d.toISOString().replace(/T|Z|\.\d{3}/g, ' ').trim();
console.log(str);

Parse Date "01/01/2016 Fri"

I am trying to parse a date in JavaScript, but the particular format is giving me fits. I have exported data from my credit card company and the format of the date field is not compatible with Date.parse or moment().isValid().
E.g.
Date.parse("01/01/2016 Fri") // NaN
moment("01/01/2016 Fri") // false
I'm not sure if I should do something with a RegEx .test() or .matches() because this is being used for a CSV import utility where dates may be in different formats. I was surprised the utility functions above didn't work.
Look in the Moment docs to see how to parse a date in any format. The first argument is the date string, the second is the format string. Alphanumeric characters are ignored, so you don't need to worry about slashes vs. dashes.
moment("01/01/2016 Fri", "MM-DD-YYYY ddd)
Check out the Mozilla MDN on Date.parse():
The parse() method takes a date string (such as "Dec 25, 1995") and
returns the number of milliseconds since January 1, 1970, 00:00:00
UTC. This function is useful for setting date values based on string
values, for example in conjunction with the setTime() method and the
Date object.
Given a string representing a time, parse() returns the time value. It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US
time zone abbreviations, but for general use, use a time zone offset,
for example, "Mon, 25 Dec 1995 13:30:00 +0430" (4 hours, 30 minutes
east of the Greenwich meridian).
From this, it looks like your problem is that you're giving the date in the improper format:
It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT".
Check this out:
Invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:
// Non-ISO string with invalid date values
new Date('23/25/2014');
TL;DR - you're passing the values in a format that is not recognized, which is why it's returning NaN.
Try this source for Regexes for dates: Regexlib.com. The site is a little out of date, but the info is great. It has tons of different Regexes for different date formats.

Parse date string with different date format

I would like to know how to parse date strings that could have different date format.
For now I do the following to parse my date strings:
var parseDate = d3.time.format("%Y-%m-%d %H:%M").parse;
How to specify multiple date format to my parseDate function?
new Date('YOUR DATE STRING')
Also checkout moment.js,
You can use moment('YOUR DATE STRING')
moment will try to interpret the String according to standard formats, if not it will fall back to Javascript's native Date() constructor.
This should work for standard ISO format or a variety of commonly seen date formats. Obviously it is not magic and will not understand all possible permutations of YYYY MM and DD

Date conversion and manipulation in javascript with Arabic months

I want to change an arabic long-form date, i.e.
الخميس 26 فبراير 2015
(Thursday 26th February, 2015)
into a standard date using standard Javascript in order to manipulate the date (add a day), then display via Date.toLocaleDateString() to convert it back, making
2015 الخميس 27 فبراير
(Friday 27th February, 2015)
Is this a case of picking the date string apart, interpreting the arabic text as a month number and creating a new Date() given the numbers, or is there a prototype that converts an arabic date string into a javascript date? What language and optional parameters need to be used for Date.toLocaleDateString() to produce the same format of arabic date, as using 'ar' the numbers are returned in eastern arabic, as opposed to the required western numerals?
var months = ["يناير", "فبراير", "مارس", "إبريل", "مايو", "يونيو",
"يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"];
var days =["اﻷحد","اﻷثنين","الثلاثاء","اﻷربعاء","الخميس","الجمعة","السبت"];
var date = new Date();
console.log("The current month is " + months[date.getMonth()]);
console.log("The current day is " + days[date.getDay()]);

Categories