javascript Date.parse() parsing non-dates - javascript

I'm trying to loop through an array and work out which items are dates. To do this I am running the values through Date.parse(value), which is supposed to only parse valid dates.
The problem is that this string is parsed as a date
"Test Title 1"
Example: http://jsfiddle.net/jonhobbs/LHeQ8/
This tells me that you can't trust Date.parse at all but I don't know of an alternatve. I've tried the moment.js library and that gives me the same thing as it uses Date.parse() internally.

Answer was to use a regex instead.

Related

Vue JS - Retrieve date only

I'm making an api call which retrieves a set of objects. One of the objects returns a date and time together like this:
createdAt: "2020-11-04 09:48:32"
This is where I display the date and time:
<template v-for="item in collectedTrash">
<BeforeAndAfter v-if="item.isPresented === 1"
:key="item.username"
:avatarUrl="require('#/assets/img/images/img_stats_km#2x.png')"
:imageBefore="getImageUrl(item.imageUrlBefore)"
:imageAfter="getImageUrl(item.imageUrlBefore)"
:username="item.username"
:date="item.createdAt"/> This is where I get the date
</template>
Is there anyway that I can retrieve the date only, rather than the date and time?
I am assuming you don't have access to the api and therefore have to process the date in your vue application.
Do you need the date as a date Object or is a string fine?
If a string representation is enough, you could use a library such as Date fns and use the format function:
...
:date="format(new Date(item.createdAt), 'yyyy-MM-dd')"
Another option might be to only use the first 10 characters of the string you received as the date: date="item.createdAt.substring(0,9)"
Did you try something like: :date="item.createdAt.substr(0, 10)"
In my experience the easiest way to format datetimes in JS it to use the Moment.js library (https://momentjs.com/). You could reformat the datetime string before passing it to your child component.
Or, if you don't want to rely on a third-party library and you know that the datetime string will always be passed in that format, I suppose you could do item.createdAt.slice(0, 10).
Moment.js can be very helpful with dates and times
Moment Docs
moment("String").format('L'); // 04/11/2020

Detect if string is a Date with an exact given format

I'd like to check whether a string does represent a Date with an given format.
I tried Date.parse(string, format) but it parses the string to date even if it's in a whole different format. E.g.:
Date.parse("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date
Date.parse("2000", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date also`
I don't want to parse the second row as a date, because its not in the required format.
I also tried Date.parseExact() method of Date.js but it didn't parsed the date if I provided a timezone and a format like above.
The right solution was based on RobG's comment: (but thanks to everyone for helping me)
moment("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ", true).isValid()
Every other solution succeeded the parsing even if the input was only a year which I tried to avoid. The last parameter "true" stands for the "strict" parsing which provides exactly the output that I was looking for.
You can leverage MomentJS and its function .format()
How does it work? here is the documentation, it's fairly simple, you wanna use your string in combination with the format string.
MomentJS .format()
And here is the quick demo Fiddle:
var myString = "2015-07-04T23:10:00.000+02:00";
var formatString = "yyyy-MM-ddTHH:mm:ss.SSSZ";
if (moment(myString, formatString)._i == myString) console.log("GOOD");
1-liner with momentJS
I basically format your string in targeted format then check if the result matches your string.
Worth noting is that MomentJS is (IMHO) the best date and time lib for JS. I never found a reason to venture beyond it since I discovered it, after using some of the less capable libs in the past.
If you don't wanna use lib, making a regex to suit your needs is a viable alternative of similar length.
Altho, if you intend to work with a lot of dates/times, MomentJS is still a way to go as it offers so many useful things which cannot be done by regexes alone.
Why not use regular expression to check if input matches the format and parse it if it does?
reg=new RegExp(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}\:[0-9]{2}\:[0-9]{2}\.[0-9]{3}\+[0-9]{2}\:[0-9]{2}/);
str="2015-07-04T23:10:00.000+02:00";
date=new Date(str);
if(str.match(reg) && date.toString()!='Invalid Date')
{
Date.parse(str);
}
Edited to add date check.

How to filter a date response to show data from today's date only?

Using GET I receive an array and one of the data items is a timestamp string in the format:
"date":"2017-01-11 12:19:15",
I have a function that needs to show specific data from this GET request for the current day only.
I think I would need to run an each loop and select only items that have the date: "2017-05-28", ignoring the "12:19:15" part.
Is there an easy and clean way to do this?
Many thanks!
Use Date.parse() (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) to parse the date, then iterate over the list of parsed dates, only selecting those within the range you seek.
When using Date.parse(), you might want to be familiar with this Why does Date.parse give incorrect results?

Moment.js compare two date thrown a warning

I have created a simple app, which need a date comparison. I used Moment.js, and I have tried on answer on this question:
Compare two dates in JS
Moment js date time comparison
How to compare only date in moment.js
But all of them not working for me.
and now I use this code:
if(moment('09/12/2016').isAfter('09/11/2016')){
console.log("True")
} else {
console.log("False")
}
But in the console it's thrown a warning:
Deprecation warning: moment construction falls back to js Date. This
is discouraged and will be removed in upcoming major release. Please
refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Everybody please help me. here's my fiddle https://jsfiddle.net/gq6ykw8L/
Your date string is ambiguous between DD/MM/YYYY and MM/DD/YYYY. If you refer to the link given in the warning (http://momentjs.com/guides/#/warnings/js-date/), it says:
This deprecation warning is thrown when no known format is found for a
date passed into the string constructor. To work around this issue,
specify a format for the string being passed to moment().
You need to use moment(String, Format) to specify the format of your date string.
moment('09/12/2016', 'DD/MM/YYYY');
moment('09/12/2016', 'MM/DD/YYYY');

JavaScript date() Object returns NaN with getYear (and other)

I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));

Categories