Date Parsing and Validation in JavaScript - javascript

How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}

Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
This will return a decimal number, so probably you'll want to look at the integer-value:
alert(Math.floor(diffInDays));

To get the date difference in days in plain JavaScript, you can do it like this:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
However if you want to get more control in your date manipulation I suggest you to use a date library, I like DateJS, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();

You can use this to check for valid date
function IsDate(testValue) {
var returnValue = false;
var testDate;
try {
testDate = new Date(testValue);
if (!isNaN(testDate)) {
returnValue = true;
}
else {
returnValue = false;
}
}
catch (e) {
returnValue = false;
}
return returnValue;
}
And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered
function IsMoreThan31Days(dateToTest) {
if(IsDate(futureDate)) {
var futureDateObj = new Date();
var enteredDateObj = new Date(dateToTest);
futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.
//adds hours and minutes to dateToTest so that the test for 31 days is more accurate.
enteredDateObj.setHours(futureDateObj.getHours());
enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);
if(enteredDateObj >= futureDateObj) {
return true;
}
else {
return false;
}
}
}

Hello and good day for everyone
You can try Refular Expressions to parse and validate a date format
here is an URL yoy can watch some samples and how to use
http://www.javascriptkit.com/jsref/regexp.shtml
A very very simple pattern would be: \d{2}/\d{2}/\d{4}
for MM/dd/yyyy or dd/MM/yyyy
With no more....
bye bye

Related

JavaScript - Get system short date format

Is there any way to get system short date format in JavaScript?
For example whether system's short date is in American format eg. m/d/Y or in european eg. d/m/Y
Please note:
This is not question about formatting date or calculating it based on geolocation, but about getting the format from the OS/system
After a pinch of research I concluded that technically it's not possible to get regional settings -and by this, date format- but you can do several other things. Pick one of these options:a) The already mentioned -and outdated- "toLocaleString()" function:
var myDate = new Date(1950, 01, 21, 22, 23, 24, 225);
var myDateFormat = myDate.toLocaleString();
alert (myDateFormat);
ISSUES:1) You can't "myDateFormat.replace" to get the date mask as month is not stored as "01", "02", etc in the string but as text instead, based on locale (like "February" in English but it's "Φεβρουάριος" in Greek and who knows what in e.g. Klingon).2) Different behavior on different browsers3) Different behavior on different OS and browser versions...b) Use the toISOString() function instead of toLocaleString(). You won't get the locale date mask but get a date from which you can tell where's which part of the date (ie where "month" or "day" is in that string). You can also work with getUTCDate(), getUTCMonth() and getUTCDay() functions. You still can't tell what date format the client uses, but can tell which Year/Month/Day/etc you work with when you grab a date; use the code above to test the functions I mentioned here to see what you can expect.c) Read
Inconsistent behavior of toLocaleString() in different browser article and use the (IMHO great) solution described there
for my case i used a custom date that i know what number is day, what is month and what is year so it can possible with a simple replace statement.
let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("12", "MM")
.replace("18", "DD")
.replace("2222", "yyyy");
It is not possible. You can get culture from user browser and use some js libraries to convert to correct date format. http://code.google.com/p/datejs/
I made a function to determine the client date format. The function determine
the date format separator, and also determine the 1st, 2nd and third part of
the date format.
getDateFormat(){
// initialize date value "31st January 2019"
var my_date = new Date(2019,0,31);
console.log(my_date.toLocaleDateString());
// Initialize variables
var separator="";
var first="";
var second="";
var third="";
var date_parts = [];
// get separator : "-", "/" or " ", format based on toLocaleDateString function
if (my_date.toLocaleDateString().split("-").length==3){
separator = " - ";
date_parts = my_date.toLocaleDateString().split("-");
}
if (my_date.toLocaleDateString().split("/").length == 3) {
separator = " / ";
date_parts = my_date.toLocaleDateString().split("/");
}
if (my_date.toLocaleDateString().split(" ").length == 3) {
separator = " ";
date_parts = my_date.toLocaleDateString().split(" ");
}
// get first part
if (date_parts[0]==2019){
first ="yyyy";
} else if (date_parts[0] == 31){
first = "dd";
} else{
if (date_parts[0].length<=2){
first ="mm";
}
else{
first="mmm";
}
}
// get second part
if (date_parts[1] == 2019) {
second = "yyyy";
} else if (date_parts[1] == 31) {
second = "dd";
} else {
if (date_parts[1].length <= 2) {
second = "mm";
}
else {
second = "mmm";
}
}
// get third part
if (date_parts[2] == 2019) {
third = "yyyy";
} else if (date_parts[2] == 31) {
third = "dd";
} else {
if (date_parts[2].length <= 2) {
third = "mm";
}
else {
third = "mmm";
}
}
// assembly
var format = first + separator + second + separator + third;
console.log(format);
return format;
}
I've created a workaround to determine which format the user's browser is using.
This is in C# but the logic is the same:
Here are the steps:
First try to convert the user's browser date into American format (mm-dd-yyyy). Convert.ToDateTime is using the American date format.
If that fails it means the user is using European format (dd-mm-yyyy).
However, this will only cover the day 13 to 31 because this is not a valid month.
If the conversion is successful, do another check to determine if the converted date is between the current UTC day + 1 day (to cover UTC+14) and current UTC day - 1 day (to cover UTC-12).
https://www.timeanddate.com/time/current-number-time-zones.html
If the converted date is out of the current date range, it means the user's browser is using European format (dd-mm-yyyy) and you can convert it to American format if you want.
string localeDateString = "01/11/2020"; // e.g. input is using European format (dd-mm-yyyy)
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
//var checkTheFormatOfDateInput = localeDate.ToLongDateString();
var currentDateTime = DateTime.UtcNow;
//var currentDateTime = Convert.ToDateTime("11/01/2020");
//var checkTheFormatOfCurrentDate = Convert.ToDateTime("11/01/2020").ToLongDateString();
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
//var checkTheEndResultFormat = localeDate.ToLongDateString();
Below is the clean code wrapped in a method:
private DateTime ConvertAmericanOrEuropeanDateFormatToAmericanDateFormat(string localeDateString)
{
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
var currentDateTime = DateTime.UtcNow;
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
return localeDate;
}
A very good but lengthy answer can here found here: https://stackoverflow.com/a/9893752/2484903
A shorter one here:
let customDate = new Date(2222, 3, 8);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("04", "MM")
.replace("4", "M")
.replace("08", "dd")
.replace("8", "d")
.replace("2222", "yyyy")
.replace("22", "yy");
console.log(format);
We create a date object of a known date and then parse the outcome.
First we look for "04" (which corresponds to 3 from the date definition); that would be the two digit month format MM. If not found, it must be the single digit format M. Afterwards do the same for day and year.
It should do the job...
function getSystemDateLocale(){
let testDate = (new Date('2000-1-30')).toLocaleDateString()
if (testDate.substring(0,2) == '30') return 'EU'
else return 'US'
}
Use Date.CultureInfo.formatPatterns.shortDate

Need explanation of this Date Processing function

Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
​function ​daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.

Date formatting and comparing dates

I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.
Please see what I have below so far:
var created = '25-05-2012 02:15';
var now = new Date();
if (created < now) {
created_format = [ format the date to be 25-05-2012 ]
} else {
created_format = [ format the date to be 02:15 ]
}
I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.
Start by getting the parts of your date string:
var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date();
// Test if it's today
if (bits[0] == now.getDate() &&
bits[1] == (now.getMonth() + 1) &&
bits[2] == now.getFullYear() ) {
// date is today, show time
} else {
// date isn't today, show date
}
Of course there are other ways, but I think the above is the easiest. e.g.
var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
// otherDate is before today
} else {
// otherDate is not before today
}
Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.
You can use getTime method and get timestamp. Then you can compare it with current date timestamp.

Compare dates javascript

I need to validate different date's with some javascript(jquery).
I have a textbox with, the inputmask from jquery (http://plugins.jquery.com/plugin-tags/inputmask). The mask that i use is "d/m/y".
Now i have set up a CustomValidator function to validate the date.
I need 2 functions. One to check if the given date is greater then 18 years ago. You must be older then 18 year.
One function to check if the date is not in the future. It can only in the past.
The function are like
function OlderThen18(source, args) {
}
function DateInThePast(source, args) {
}
As you know the value you get back with args.Value is 27/12/1987 .
But how can i check this date in the functions? So that i can set args.IsValid to True or False.
I tried to parse the string(27/12/1987) that i get back from the masked textbox to a date but i get always a value back like 27/12/1988.
So how could I check the given dates with the other dates?
The simple way is to add 18 years to the supplied date and see if the result is today or earlier, e.g.:
// Input date as d/m/y or date object
// Return true/false if d is 18 years or more ago
function isOver18(d) {
var t;
var now = new Date();
// Set hours, mins, secs to zero
now.setHours(0,0,0);
// Deal with string input
if (typeof d == 'string') {
t = d.split('/');
d = new Date(t[2] + '/' + t[1] + '/' + t[0]);
}
// Add 18 years to date, check if on or before today
if (d.setYear && d.getFullYear) {
d.setYear(d.getFullYear() + 18);
}
return d <= now;
}
// For 27/4/2011
isOver18('27/4/2011'); // true
isOver18('26/4/2011'); // true
isOver18('28/4/2011'); // false
try this to start:
var d = new Date(myDate);
var now = new Date();
if ((now.getFullYear() - d.getFullYear()) < 18) {
//do stuff
}
The javascript date object is quite flexible and can handle many date strings.
You can compare two Date objects or use the Date interface methods, such as getSeconds() of getFullYear() in order to deduce useful data regarding the date.
See Date object reference formore details.
You'll need to construct, modify and compare Date objects - something like this:
// str should already be in dd/mm/yyyy format
function parseDate(str) {
var a = str.split('/');
return new Date(parseInt(a[2], 10), // year
parseInt(a[1], 10) - 1, // month, should be 0-11
parseInt(a[0], 10)); // day
}
// returns a date object for today (at midnight)
function today() {
var date = new Date();
date.setHours(0, 0, 0);
return date;
}
function DateInThePast(str) {
// date objects can be compared like numbers
// for equality (==) you'll need to compare the value of date.getTime()
return parseDate(str) < today();
}
function OlderThan18(str) {
// left as an exercise for the reader :-)
}

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources