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');
Related
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.
I am using _i in momentjs with if condition but it is not giving expected output.
Here is my code:
var output = "07-14-2017";
var selectedDates = "06-15-2018";
if(moment(output)._i <= moment(selectedDates)._i)
{
console.log(output date is less than or equal selected date);
}
else
{
console.log(output date is greater than selected date);
}
Here my output date is of 2017 and selecteddates is of 2018, still it is giving me an output of 'output date is greater than selected date'. It should give me an output 'output date is less than or equal selected date'.
I have given all jQuery and momentjs files references properly.
There are 2 issue with your code:
You are trying to parse using moment(String) a string that is neither in RFC2822 or ISO 8601 recognized format, so your code gives Deprecation warning. You have to use moment(String, String) instead.
You are using _i that as Internal Properties guide states:
[...] the values of _d and any other properties prefixed with _ should not be used for any purpose.
To compare moment objects you can use isSameOrBefore, isAfter, isBefore and the others methods listed in the Query section of the docs.
Here a working sample:
var output = "07-14-2017";
var selectedDates = "06-15-2018";
if(moment(output, 'MM-DD-YYYY').isSameOrBefore(moment(selectedDates, 'MM-DD-YYYY')))
{
console.log("output date is less than or equal selected date");
}
else
{
console.log("output date is greater than selected date");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_i returns string which is not correct and also you should not use it as per #Andreas comments.
You can use below code gives correct comparison.
moment(selectedDates).isAfter(output);
I just tested your code and it works in Chrome 59, however it threw the following warning:
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date(), which is not
reliable across all browsers and versions. Non RFC2822/ISO date
formats are discouraged and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
It's possible that your issues are with your browser's javascript engine's implementation of Date(), as hinted in the warning above.
I would recommend you reformat your dates to a more moment-friendly format and try again.
Following date formatting is not working in momentJs
var date ="01-12-2015";//DD-MM-YYY
console.info(moment(date).format('YYYY-MM-DD'));
How can I solve this?
You need to tell momentJS how to parse the string you are giving:
var date ="01-12-2015";//DD-MM-YYYY
console.info(moment(date, 'DD-MM-YYYY').format('YYYY-MM-DD'));
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Try this..
var date ="01-12-2015";//DD-MM-YYY
date = date.replace(/-/g,"/")
console.info(moment(new Date(date)).format('YYYY-MM-DD'));
I was looking for this very specific conversion which I couldnt find anywhere
var d = new Date("2014-12-25T18:30:00+0100");
console.log(d.toString());
the console.log returns an "Invalid Date"
The DateString is returned by the Facebook GraphAPI.
What am I doing wrong? can anyone help?
Thanks in advance
EDIT:
Now that I fixed the API my output is kind of consfusing:
I tried splitting up the String
d.getDay()+'.'+d.getMonth()+'.'+d.getYear()+' '+d.getHours()+':'+d.getMinutes();
it outputs
4.11.114 18:30
why?!
Instead of doing those complicated date functions
d.getDate()+'.'+d.getMonth()+'.'+d.getYear()+' '+d.getHours()+':'+d.getMinutes();
Do yourself a favour and include http://momentjs.com/ in your project. You can then simply take the date from the facebook api and format it with
moment("2014-12-25T18:30:00+0100").format("/* date format */");
See here for formating
SIDENOTE
When formating dates in plain javascript, you will have to add 1 month to your month - january is 0, that's why you get 4.11... instead of 4.12...
Change getYear() to getFullYear()
d.getDay()+'.'+d.getMonth()+'.'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();
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.