IsSame and IsAfter condition not working in moment.js - javascript

I am validating the dates using moment.js
var dobfield = $("#dobfield").val().trim();
//...
formatToApply = "DD/MM/YYYY";
//...
else if(moment(dobfield, formatToApply).isAfter(moment().format(formatToApply)))
{
swal({
title: "",
text: "Date of birth has to be in the past! "
});
$("#dobfield").focus();
}
else if(moment(dobfield, formatToApply).isSame(moment().format(formatToApply)))
{
swal({
title: "",
text: "Date of birth cannot be in the present! "
});
$("#dobfield").focus();
}
Both the isSame and isAfter fails to validate the date given in dd/mm/yyyy format.

I assume you just want to compare just the date, not the time. So you have to indicate that to the isSame() and isAfter() functions...
var dobfield = $("#dobfield").val().trim();
...
formatToApply = "DD/MM/YYYY";
...
else if (moment(dobfield,formatToApply).isAfter(moment(),'day')) {
swal({
title: "",
text: "Date of birth has to be in the past! "
});
$("#dobfield").focus();
}
else if (moment(dobfield,formatToApply).isSame(moment(),'day')) {
swal({
title: "",
text: "Date of birth cannot be in the present! "
});
$("#dobfield").focus();
}
Here you have a fiddle example... https://fiddle.jshell.net/rigobauer/mz9rutuq/
NOTE: dobfield date format always has to match with the format specified in formatToApply variable. Otherwise, moment(dobfield,formatToApply) will get unexpected result.

In my case the issue is outdated version of moment.js

Sadly , moment.js isAfter and isSame is not wokring for this date format . it is only working for YYYY-MM-DD .
This is a bug from moment.js i could say .

Related

Function to get the input provided to momentjs

Is there any function to get the input that was provided to moment()
In the example below, inputDate becomes null.
var date = moment("invalid date");
if(!data.isValid()){
return { message: "Invalid date", inputDate: date }
}
I can access the input using internals i.e. date._i but was wondering if there's any function that would return the input provided to moment constructor.
You can use creationData()
After a moment object is created, all of the inputs can be accessed with creationData() method:
moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
input: "2013-01-02",
format: "YYYY-MM-DD",
locale: Locale obj,
isUTC: false,
strict: true
}
Here a live example:
var date = moment("invalid date", moment.ISO_8601);
console.log(date.creationData().input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
As a side note:
I've used moment.ISO_8601 in my snippet to prevent Deprecation Warning, as shown here.
Something quite similar was asked (but not a duplicate) was asked here.

Moment.js Invalid date message

Im exploring moment.js with Datatables, and its really good for showing the date in the format that I want but there is a problem that i have with the data that I am converting.
If the date is not valid it shows the message INVALID DATE, wihch is good but not what I really want.
Is it possible to, insted of showing "Invalid Date" message, show what was in there originally?
Like if it is not a date I want to see what it is, not that message.
Thanks!
EDIT:
Thanks for your help guys!
I have done this for the datatable "aoColumns":
{ "mData": "APE",
"render": function(mData){
if(mData != null){
if(moment(mData).format("DD/MM/YYYY")== 'Invalid date')
{
return mData;
}
else
{
return moment(mData).format("DD/MM/YYYY");
}
}
},
sDefaultContent: ''},
moment.updateLocale(moment.locale(), { invalidDate: "ur msg or NaN/null" });
var dateStr = "aw 2017-06- awd 09 10:05:21.0";
//var dateStr = "a2017-06-09 10:05:21.0";
if(moment(dateStr, moment.ISO_8601).isValid()){
alert("Valid Date: " + moment(dateStr).format('MM/DD/YYYY'));
}
else {
alert("Invalid Date: " +dateStr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Try creating your own function where you check if the date is valid or not,
see moment validation and if it is not valid return the original data for the message.
Update: Please see this post for extra explanation on the code snippet
Depending on how you've implemented Moment.js, you could simply check the return value from moment? For example
var prettyDate = moment()...;
if(prettyDate != 'Invalid date') {
// set your date
}

JS Date "Too many Recursions"

I have a piece of code to validate date ranges that Works in Chrome, but not in IE or Firefox.
I am using Kendo DateTimePicker to get the user dates. For example, if DateTo is an earlier date than DateFrom, DateFrom will be automatically change to the same date as DateTo.
if (dateFromEpochTime > dateToEpochTime) {
date = dateFrom.data("kendoDateTimePicker").value();
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
dateTo.kendoDateTimePicker({
value: date,
format: "dd-MM-yyyy HH:mm:ss"
})
changedByCode = true;
}
} else {
if (dateFromEpochTime > dateToEpochTime) {
date = dateTo.data("kendoDateTimePicker").value();
date.setHours(00);
date.setMinutes(00);
date.setSeconds(00);
dateFrom.kendoDateTimePicker({
value: date,
format: "dd-MM-yyyy HH:mm:ss"
})
changedByCode = true;
}
}
This pieces of code that throw the exceptions(Too many recursions for Firefox and Out of stack space for IE) are:
dateTo.kendoDateTimePicker({ value: date, format: "dd-MM-yyyy HH:mm:ss" })
dateFrom.kendoDateTimePicker({ value: date, format: "dd-MM-yyyy HH:mm:ss" })
I cant quite figure out what goes wrong there.
P.s: Before the user presses Ok, I can change the dates as many times as I want and my function will correct them. After I press Ok and try to repeat the action things are breaking. Also, I am not including the same JavaScript file twice.

Sort date in table

I want to convert string to date in Javascript. I need to do it because I have an array and create table from that. After that I want to use Tablesorter. But it sort it only like textfield. I trying to create new parser. I have string like:
"02 January 2010"
I need to create date type from that. Is it possible in Javascript? I tried
DateFormat format = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
Date date = format.parse(s);
But it doesnt work. How would I do that?
With a standard date format, you can create a date parser that doesn't need to reformat the date (demo)
$(function () {
$.tablesorter.addParser({
id: 'ddMMMMyyyy',
is: function() {
return false;
},
format: function(s) {
var date = new Date(s);
return date instanceof Date && isFinite(date) ? date.getTime() : s;
},
type: 'numeric'
});
$('table').tablesorter({
headers : {
5: { sorter: 'ddMMMMyyyy' }
}
});
});

javascript date validation

Assume in my text box user enter like
18-06-2010 ,
Validation RULE if date is greater then current date then program should through the validation error like ,
PELASE ENTER PAST OR CURRENT DATE, DONT CHOOSE FUTURE DATE ,
Thanks
The date format you've specified is not recognized by javascript. Here's a script that makes some minor validity checking, but still some rough assumptions that the value entered conforms to the format above, and tries to construct the date string '2010/06/08' out of that.
var txtDate = document.getElementById('myTextBox').value;
var dateParts = txtDate.split('-');
if(dateParts.length != 3) {
alert('invalid date!');
return false;
}
var testDate = new Date(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);
if(isNaN(testDate.getDate())) {
alert('invalid date!');
return false;
}
Implement further error checking as you see fit. Once you know testDate is a date, you can compare it the current date: testDate > new Date()

Categories

Resources