Validating a UK date using Javascript/jQuery - javascript

I have two jQuery datepickers that once changed, will trigger some ajax to grab all information between the two dates.
I want to run some code to check that the first date is smaller than the second, by converting to a date using this code:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
return new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
}
This works great, but the problem is even if I enter a date of '50/08/2011' it still validates and converts that to a Javascript date, I believe by adding the additional number of days to the start date.
Is there a way to properly validate this please?
Thanks!

you can validate using a jquery masked plugin,you can check it http://digitalbush.com/projects/masked-input-plugin/

For working with dates you can try to use datejs library. It has many features including validating dates. To solve your problem you can use Date.validateDay method. Also you can use datejs to compare dates.

hm... I guess a plugin would be a better solution, but for what it's worth:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
var newDate = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
return newDate.getDate() == Number(dateStr[0]) && newDate.getMonth() == Number(dateStr[1]) - 1? newDate : null;
}
returns null if the date carries over to the next month.
Edit
New code :P

Related

Unable to set Date Format with Javascript

I am trying to collect a date from text boxes and then do a comparison on them. I am entering the dates in dd-MM-yyyy format, however when the comparison is running its running is in a MM-dd-yyyy format.
my fiddle is here
in my live application I am using a bootstrap datepicker to enter the date so the date entered will always be the correct format.
Ive looked here at W3 Schools and I have also tried looking at
var dt1 = d1.split(/\-|\s/)
var dt2 = d2.split(/\-|\s/)
dat1 = new Date(dt1);
dat2 = new Date(dt2);
dat1.format("dd-MM-yyyy")
but this also fails.
Any and all help very much appreciated.
thanks
Use the getTime() method if you want to make comparison on dates :
if(dat1.getTime() > dat2.getTime()) { ... }
On your example : https://jsfiddle.net/3ut8a7zj/1/

Can't Compare dates using jQuery UI's datepicker

Ok, so I am attempting to test if a date is older than today. I am using jQuery UI's Datepicker to parse the date and assign it to a variable:
//Get Date as String
var $strDate = $(".pmt-date").text();
//Parse Date
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Then I get today's date and assign it to a variable:
//Get Today's Date
var $strToday $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
Now I would like to compare $dtDate with $tDate. This is what I have tried:
if($dtDate > $tDate)
{
alert("Payment Date is Greater");
}
else
{
alert("Today's Date is Greater");
}
When I test this, I ALWAYS get the alert "Today's Date is Greater". I can display my two date variables via an alert, and I see the dates in correct format. So why does this comparison fail to work when the parse is working correctly?
Assuming that the field with class "pmt-date" is the datepicker-controlled <input> element, you need to fetch its value with .val(), not .text().
var $strDate = $(".pmt-date").val();
Your next line of code refers to a variable called "$date", not "$strDate", so:
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Once you've got that, you can just directly compare the Date objects:
if ($dtDate < new Date())
There's no need to turn a newly-constructed Date object into a string and then back into a date. I guess you're Date to string and back in order to strip off the time-of-day part of the date, so that's not really a bad way to do it.
In date comparisons, more than means the date comes after, and less than means the date comes before. Older than would imply that the date comes before, and thus you want to use less than
if($dtDate < $tDate)

How to set datetime on datetime-local via jQuery

I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?
<input type="datetime-local" id="publishDate" required/>
I tried
$("#publishDate").val("2013-3-18 13:00");
$("#publishDate").val("2013-3-18T13:00");
$("#publishDate").val(new Date().toLocalString());
but nothing worked.
This would do the trick
$("#publishDate").val("2013-03-18T13:00");
You need to use 2 digits for the month to make your sample work.
If you want to set the current date, then you can try this:
__Method 1:__
$(document).ready(function(){
$('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});
__Method 2:__
function zeroPadded(val) {
if (val >= 10)
return val;
else
return '0' + val;
}
$(document).ready(function(){
d = new Date();
$('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});
Note: You can replace $('input[type=datetime-local]') with Id or Name or Class of the datetime-local field.
EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.
What about?
var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));
I wrote a jQuery method that sets the current UTC time. It's useful for initializing datetime and datetime-local input fields.
Here's how you would use it to initialize a field.
$('input[type="datetime"]').setNow();
Or pass an argument of true to only set fields with no value.
$('input[type="datetime"]').setNow(true);
Here's a solution in formatting the date using momentjs.
This will get the current date and time
moment().format('YYYY-MM-DDThh:mm:ss.SSS')
Here is a simpler way to do it.
const now = (new Date().toLocaleString("sv-SE") + '').replace(' ','T');
console.log(now);
This component is messed up because it's not specified properly yet. Implementations are likely to be quirky as well.
The right way to do it should be to pass a date object, with JS and DOM it would make no sense to not have this. Doing things with string manipulation is going to invoke Zalgo. Sooner or later it will break with the locale or timezone.
I have looked for something like this and in Chrome 46 found:
$('input[type=datetime-local]').prop('valueAsNumber', Math.floor(new Date() / 60000) * 60000); // 60seconds * 1000milliseconds
If you don't remove the second and milliseconds they will show in the input field.
There is a valueAsDate property as well but mysteriously:
Uncaught DOMException: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.
So they haven't finished implementing it yet or choose a bad name for that property (it shows as null even when something is set though).
for those who have date in string format with "T" character in between,
replace the 10 character (space) with T
with below code:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
var variable=setCharAt("2022-02-26 16:32",10,"T");
$("#publishDate").val(variable);
but remember that the format must be in "YYYY-MM-DDThh:mm:ss"
the OP has made the mistake of providing date "2013-3-18T13:00"
where as the month should have been "03"
Using moment, you can do the following.
If you want to use the current date.
$("#publishDate").val(moment().format('YYYY-MM-DDTHH:MM'));
If you have a specified date.
$("#publishDate").val(moment(yourDate).format('YYYY-MM-DDTHH:MM'));

how to check if one date comes before anotherone in javascript

I have 2 dates and I one to check if one date comes before another one.
I know you have to parse the date to a JS date object and then check it with milliseconds.
But the problem is, in my database dateTimes are stored like this.
10-mei-2012 09:36
So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.
var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();
kind regards
Stef
In that format you can compare strings as-is, it is safe. So use just
if (dateB < dateE) ...
http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.
The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.
The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.
http://en.wikipedia.org/wiki/ISO_8601
So, if you can sort the strings you know which one comes first.
Here's a function found while googling that converts MySQL DATETIME to a JS Object
function mysqlTimeStampToDate(timestamp) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
Here's one example of how to use it:
$(function(){
var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());
if(dateB < dateE){
// dateB is older
} else {
// dateB is newer
}
});

Calculate date difference in integer value

I have two date fields with IDs gp_vdate_from and gp_vdate_to. And I have a hidden div which is populated by a dynamic table. The div gets visible on click of a button after entering date fields. I did something like this to calculate the date difference
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.floor((second-first)/(1000*60*60*24))
}
var diff=(daydiff(parseDate($('#gp_vdate_from').val()), parseDate($('#gp_vdate_to').val())));
The date entered is in the format 10-2-2012.
But I am not able to give to get the difference? Can someone point out why?
I think you do not have valid dates. Look at this line:
new Date(mdy[2], mdy[0]-1, mdy[1])
This is like writing
new Date(2012,9,'feb')
for 10-feb-2012, which is not valid. The date constructor takes arguments like this:
new Date(year, month, day [, hour, minute, second, millisecond ]);
Where all the arguments are integers ('feb' is not valid, also you were passing arguments in the wrong order.)
So I think you need to look at your parseDate method.
This is all assuming that JQuery doesn't change how the Date object works - you may need to check that.
You should use a javascript console like Firebug for firefox to help you debug.
You can use date.getTime() to check the difference
function daydiff(first, second) {
return Math.floor((second.getTime()-first.getTime())/(1000*60*60*24));
}
please check with Date object create arguments
new Date(year,month,day);
You could try using date.js, a small but awesome JS library just for working with dates. It normalises Date objects across browsers and gives all kinds of sugary methods for working with dates :)
Can be used with jQuery too
EDIT
date.js makes working with dates less painful, but is not essential, everything you need can be done in pure JS.
Other answerers - Actually, the Date constructor in JavaScript can accept a single string as an argument, which it uses to generate a new Date object.
I made a fiddle based on your example code showing how to calculate number of days between two dates. Have a look and play around and it might be what you need :)

Categories

Resources