How to check if a given Date exists in DART? - datetime

If you pass a non-existing/non-real date like: '20181364' (2018/13/64) into DateTime (constructor or parse-method), no exception is thrown. Instead a calculated DateTime is returned.
Example:
'20181364' --> 2019-03-05 00:00:00.000
How can I check if a given date really exists/is valid?
I tried to solve this using DartPad (without success), so no Flutter doctor output required here.
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) => print(convertToDate(input)));
}
String convertToDate(String input){
return DateTime.parse(input).toString();
}
It would be great if there exist some kind of method to check if a given date really exists/is valid, e.g.:
a validate function in DateTime
another lib that does not use DateTime.parse() for validation
How would you solve this?

You can convert parsed date to string with original format and then compare if it's matching the input.
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) {
print("$input is valid string: ${isValidDate(input)}");
});
}
bool isValidDate(String input) {
final date = DateTime.parse(input);
final originalFormatString = toOriginalFormatString(date);
return input == originalFormatString;
}
String toOriginalFormatString(DateTime dateTime) {
final y = dateTime.year.toString().padLeft(4, '0');
final m = dateTime.month.toString().padLeft(2, '0');
final d = dateTime.day.toString().padLeft(2, '0');
return "$y$m$d";
}

My solution to validate the birthday was this, we can see that it has the leap year calculation.
class DateHelper{
/*
* Is valid date and format
*
* Format: dd/MM/yyyy
* valid:
* 01/12/1996
* invalid:
* 01/13/1996
*
* Format: MM/dd/yyyy
* valid:
* 12/01/1996
* invalid
* 13/01/1996
* */
static bool isValidDateBirth(String date, String format) {
try {
int day, month, year;
//Get separator data 10/10/2020, 2020-10-10, 10.10.2020
String separator = RegExp("([-/.])").firstMatch(date).group(0)[0];
//Split by separator [mm, dd, yyyy]
var frSplit = format.split(separator);
//Split by separtor [10, 10, 2020]
var dtSplit = date.split(separator);
for (int i = 0; i < frSplit.length; i++) {
var frm = frSplit[i].toLowerCase();
var vl = dtSplit[i];
if (frm == "dd")
day = int.parse(vl);
else if (frm == "mm")
month = int.parse(vl);
else if (frm == "yyyy")
year = int.parse(vl);
}
//First date check
//The dart does not throw an exception for invalid date.
var now = DateTime.now();
if(month > 12 || month < 1 || day < 1 || day > daysInMonth(month, year) || year < 1810 || (year > now.year && day > now.day && month > now.month))
throw Exception("Date birth invalid.");
return true;
} catch (e) {
return false;
}
}
static int daysInMonth(int month, int year) {
int days = 28 + (month + (month/8).floor()) % 2 + 2 % month + 2 * (1/month).floor();
return (isLeapYear(year) && month == 2)? 29 : days;
}
static bool isLeapYear(int year)
=> (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 );
}

Support for validating dates was added for dart in December 2020: https://pub.dev/documentation/intl/latest/intl/DateFormat/parseStrict.html

Related

Flutter - How to find difference between two dates in years, months and days?

I'm looking for a way to use DateTime to parse two dates, to show the difference.
I want to have it on the format: "X years, Y months, Z days".
For JS, we have momentjs library and following code::
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'year');
b.add(years, 'years');
var months = a.diff(b, 'months');
b.add(months, 'months');
var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days
Is there similar library available for dart that can help achieve this usecase?
I think it is not possible to do exactly what you want easily with DateTime. Therefore you can use https://pub.dev/packages/time_machine package that is quite powerful with date time handling:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDate a = LocalDate.today();
LocalDate b = LocalDate.dateTime(DateTime(2022, 1, 2));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}");
}
for hours/minutes/seconds precision:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDateTime a = LocalDateTime.now();
LocalDateTime b = LocalDateTime.dateTime(DateTime(2022, 1, 2, 10, 15, 47));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}; hours: ${diff.hours}; minutes: ${diff.minutes}; seconds: ${diff.seconds}");
}
What you are looking for is the Dart DateTime class
You can get close to what you want in moment.js with
main() {
var a = DateTime.utc(2015, 11, 29);
var b = DateTime.utc(2007, 06, 27);
var years = a.difference(b);
print(years.inDays ~/365);
}
There is no inYears or inMonths option for DateTime though that's why the year is divided in the print.
the difference function returns the difference in seconds so you have to process it yourself to days.
You could write an extension on duration class to format it:
extension DurationExtensions on Duration {
String toYearsMonthsDaysString() {
final years = this.inDays ~/ 365
// You will need a custom logic for the months part, since not every month has 30 days
final months = (this.inDays ~% 365) ~/ 30
final days = (this.inDays ~% 365) ~% 30
return "$years years $months months $days days";
}
}
The usage will be:
final date1 = DateTime()
final date2 = DateTime()
date1.difference(date2).toYearsMonthsDaysString()
You can use Jiffy Package for this like this
var jiffy1 = Jiffy("2008-10", "yyyy-MM");
var jiffy2 = Jiffy("2007-1", "yyyy-MM");
jiff1.diff(jiffy2, Units.YEAR); // 1
jiff1.diff(jiffy2, Units.YEAR, true);
You can calculate from the total number of days:
void main() {
DateTime a = DateTime(2015, 11, 29);
DateTime b = DateTime(2007, 06, 27);
int totalDays = a.difference(b).inDays;
int years = totalDays ~/ 365;
int months = (totalDays-years*365) ~/ 30;
int days = totalDays-years*365-months*30;
print("$years $months $days $totalDays");
}
Result is: 8 5 7 3077
I created my own class for Gregorian Dates, and I created a method which handle this issue, it calculates "logically" the difference between two dates in years, months, and days...
i actually created the class from scratch without using any other packages (including DateTime package) but here I used DateTime package to illustrate how this method works.. until now it works fine for me...
method to determine if it's a leap year or no:
static bool leapYear(DateTime date) {
if(date.year%4 == 0) {
if(date.year%100 == 0){
return date.year%400 == 0;
}
return true;
}
return false;
}
this is the method which calculates the difference between two dates in years, months, and days. it puts the result in a list of integers:
static List<int> differenceInYearsMonthsDays(DateTime dt1, DateTime dt2) {
List<int> simpleYear = [31,28,31,30,31,30,31,31,30,31,30,31];
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
int totalMonthsDifference = ((dt2.year*12) + (dt2.month - 1)) - ((dt1.year*12) + (dt1.month - 1));
int years = (totalMonthsDifference/12).floor();
int months = totalMonthsDifference%12;
late int days;
if(dt2.day >= dt1.day) {days = dt2.day - dt1.day;}
else {
int monthDays = dt2.month == 3
? (leapYear(dt2)? 29: 28)
: (dt2.month - 2 == -1? simpleYear[11]: simpleYear[dt2.month - 2]);
int day = dt1.day;
if(day > monthDays) day = monthDays;
days = monthDays - (day - dt2.day);
months--;
}
if(months < 0) {
months = 11;
years--;
}
return [years, months, days];
}
the method which calculates the difference between two dates in months, and days:
static List<int> differenceInMonths(DateTime dt1, DateTime dt2){
List<int> inYears = differenceInYearsMonthsDays(dt1, dt2);
int difMonths = (inYears[0]*12) + inYears[1];
return [difMonths, inYears[2]];
}
the method which calculates the difference between two dates in days:
static int differenceInDays(DateTime dt1, DateTime dt2) {
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
return dt2.difference(dt1).inDays;
}
usage example:
void main() {
DateTime date1 = DateTime(2005, 10, 3);
DateTime date2 = DateTime(2022, 1, 12);
List<int> diffYMD = GregorianDate.differenceInYearsMonthsDays(date1, date2);
List<int> diffMD = GregorianDate.differenceInMonths(date1, date2);
int diffD = GregorianDate.differenceInDays(date1, date2);
print("The difference in years, months and days: ${diffYMD[0]} years, ${diffYMD[1]} months, and ${diffYMD[2]} days.");
print("The difference in months and days: ${diffMD[0]} months, and ${diffMD[1]} days.");
print("The difference in days: $diffD days.");
}
output:
The difference in years, months and days: 16 years, 3 months, and 9 days.
The difference in months and days: 195 months, and 9 days.
The difference in days: 5945 days.
the answer is yes, you can easilly achieve it with DateTime class in Dart. See: https://api.dart.dev/stable/2.8.3/dart-core/DateTime-class.html
Example
void main() {
var moonLanding = DateTime(1969,07,20)
var marsLanding = DateTime(2024,06,10);
var diff = moonLanding.difference(marsLanding);
print(diff.inDays.abs());
print(diff.inMinutes.abs());
print(diff.inHours.abs());
}
outputs:
20049
28870560
481176
final firstDate = DateTime.now();
final secondDate = DateTime(firstDate.year, firstDate.month - 20);
final yearsDifference = firstDate.year - secondDate.year;
final monthsDifference = (firstDate.year - secondDate.year) * 12 +
firstDate.month - secondDate.month;
final totalDays = firstDate.difference(secondDate).inDays;
Simple approach, no packages needed.
try intl package with the following code:
import 'package:intl/intl.dart';
String startDate = '01/01/2021';
String endDate = '01/01/2022';
final start = DateFormat('dd/MM/yyyy').parse(startDate);
final end = DateFormat('dd/MM/yyyy').parse(endDate);
Then, you can calculate the duration between the two dates with the following code:
final duration = end.difference(start);
To obtain the number of years, months and days, you can do the following:
final years = duration.inDays / 365;
final months = duration.inDays % 365 / 30;
final days = duration.inDays % 365 % 30;
Finally, you can use these variables to display the result in the desired format:
final result = '${years.toInt()} years ${months.toInt()} months y ${days.toInt()} days';
DateTime difference in years is a specific function, like this:
static int getDateDiffInYear(DateTime dateFrom, DateTime dateTo) {
int sign = 1;
if (dateFrom.isAfter(dateTo)) {
DateTime temp = dateFrom;
dateFrom = dateTo;
dateTo = temp;
sign = -1;
}
int years = dateTo.year - dateFrom.year;
int months = dateTo.month - dateFrom.month;
if (months < 0) {
years--;
} else {
int days = dateTo.day - dateFrom.day;
if (days < 0) {
years--;
}
}
return years * sign;
}
difHour = someDateTime.difference(DateTime.now()).inHours;
difMin = (someDateTime.difference(DateTime.now()).inMinutes)-(difHour*60);
and same for years and days

check if datetime variable is today, tomorrow or yesterday

I do not know how to check if datetime variable is today, tomorrow or yesterday.
I did not find a method in the class members.
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final yesterday = DateTime(now.year, now.month, now.day - 1);
final tomorrow = DateTime(now.year, now.month, now.day + 1);
final dateToCheck = ...
final aDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
if(aDate == today) {
...
} else if(aDate == yesterday) {
...
} else(aDate == tomorrow) {
...
}
Hit: now.day - 1 and now.day + 1 works well with dates that result in a different year or month.
While the above answer is correct, I would like to provide a more compact and flexible alternative :
/// Returns the difference (in full days) between the provided date and today.
int calculateDifference(DateTime date) {
DateTime now = DateTime.now();
return DateTime(date.year, date.month, date.day).difference(DateTime(now.year, now.month, now.day)).inDays;
}
So if you want to check if date is :
Yesterday : calculateDifference(date) == -1.
Today : calculateDifference(date) == 0.
Tomorrow : calculateDifference(date) == 1.
Using dart extensions can help make your code more elegant. You can create a utility class with the following:
extension DateHelpers on DateTime {
bool isToday() {
final now = DateTime.now();
return now.day == this.day &&
now.month == this.month &&
now.year == this.year;
}
bool isYesterday() {
final yesterday = DateTime.now().subtract(Duration(days: 1));
return yesterday.day == this.day &&
yesterday.month == this.month &&
yesterday.year == this.year;
}
}
And then whenever you need to know if a day is today or yesterday, import the utility class into the file where you need it and then call the appropriate function like it was inbuilt in the DateTime class.
Text(
myDate.isToday() ? "Today"
: myDate.isYesterday() ? "Yesterday"
: DateFormat("dd MMM").format(myDate)
)
#34mo 's answer updated for flutter lint 2021
extension DateUtils on DateTime {
bool get isToday {
final now = DateTime.now();
return now.day == day && now.month == month && now.year == year;
}
bool get isTomorrow {
final tomorrow = DateTime.now().add(const Duration(days: 1));
return tomorrow.day == day &&
tomorrow.month == month &&
tomorrow.year == year;
}
bool get isYesterday {
final yesterday = DateTime.now().subtract(const Duration(days: 1));
return yesterday.day == day &&
yesterday.month == month &&
yesterday.year == year;
}
}
A simple isToday check:
/// Returns `true` if the [date] is today. Respects the time zone.
/// https://stackoverflow.com/a/60213219/1321917
bool isToday(DateTime date) {
final DateTime localDate = date.toLocal();
final now = DateTime.now();
final diff = now.difference(localDate).inDays;
return diff == 0 && now.day == localDate.day;
}
Simple method to check if is today
bool isToday(DateTime date) {
final now = DateTime.now();
return now.year == date.year &&
now.month == date.month &&
now.day == date.day;
}
For more simplification you can follow this steps.
String myDate = "01/09/2022";
like i need to check this "myDate" is today or tomorrow.
so,simply i call this function,
String dateConverter(String myDate) {
String date;
DateTime convertedDate =
DateFormat("DD/MM/YYYY").parse(myDate.toString());
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final yesterday = DateTime(now.year, now.month, now.day - 1);
final tomorrow = DateTime(now.year, now.month, now.day + 1);
final dateToCheck = convertedDate;
final checkDate = DateTime(dateToCheck.year, dateToCheck.month, dateToCheck.day);
if (checkDate == today) {
date = "Today";
} else if (checkDate == yesterday) {
date = "Yesterday";
} else if (checkDate == tomorrow) {
date = "Tomorrow";
} else {
date = myDate;
}
return date;
}
if myDate is not today,tomorrow or yesterday then it simply return my default date string.
This one will also do the work
String checkDate(String dateString){
// example, dateString = "2020-01-26";
DateTime checkedTime= DateTime.parse(dateString);
DateTime currentTime= DateTime.now();
if((currentTime.year == checkedTime.year)
&& (currentTime.month == checkedTime.month)
&& (currentTime.day == checkedTime.day))
{
return "TODAY";
}
else if((currentTime.year == checkedTime.year)
&& (currentTime.month == checkedTime.month))
{
if((currentTime.day - checkedTime.day) == 1){
return "YESTERDAY";
}else if((currentTime.day - checkedTime.day) == -1){
return "TOMORROW";
}else{
return dateString;
}
}
}

Get Last Month Date In Flutter / Dart

in flutter we can get current month using this
var now = new DateTime.now();
var formatter = new DateFormat('MM');
String month = formatter.format(now);
But how to get the last month date? Especially if current date is January (01). we can't get the right month when we use operand minus (-) , like month - 1.
You can just use
var prevMonth = new DateTime(date.year, date.month - 1, date.day);
with
var date = new DateTime(2018, 1, 13);
you get
2017-12-13
It's usually a good idea to convert to UTC and then back to local date/time before doing date calculations to avoid issues with daylight saving and time zones.
We can calculate both first day of the month and the last day of the month:
DateTime firstDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month, 1);
DateTime lastDayCurrentMonth = DateTime.utc(DateTime.now().year, DateTime.now().month + 1).subtract(Duration(days: 1));
DateTime.utc takes in integer values as parameters: int year, int month, int day and so on.
Try this package, Jiffy, it used momentjs syntax. See below
Jiffy().subtract(months: 1);
Where Jiffy() returns date now. You can also do the following, the same result
var now = DateTime.now();
Jiffy(now).subtract(months: 1);
We can use the subtract method to get past month date.
DateTime pastMonth = DateTime.now().subtract(Duration(days: 30));
Dates are pretty hard to calculate. There is an open proposal to add support for adding years and months here https://github.com/dart-lang/sdk/issues/27245.
There is a semantic problem with adding months and years in that "a
month" and "a year" isn't a specific amount of time. Years vary by one
day, months by up to three days. Adding "one month" to the 30th of
January is ambiguous. We can do it, we just have to pick some
arbitrary day between the 27th of February and the 2nd of March.
That's why we haven't added month and year to Duration - they do not
describe durations.
You can use the below code to add months in a arbitrary fashion (I presume its not completely accurate. Taken from the issue)
const _daysInMonth = const [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
bool isLeapYear(int value) =>
value % 400 == 0 || (value % 4 == 0 && value % 100 != 0);
int daysInMonth(int year, int month) {
var result = _daysInMonth[month];
if (month == 2 && isLeapYear(year)) result++;
return result;
}
DateTime addMonths(DateTime dt, int value) {
var r = value % 12;
var q = (value - r) ~/ 12;
var newYear = dt.year + q;
var newMonth = dt.month + r;
if (newMonth > 12) {
newYear++;
newMonth -= 12;
}
var newDay = min(dt.day, daysInMonth(newYear, newMonth));
if (dt.isUtc) {
return new DateTime.utc(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
} else {
return new DateTime(
newYear,
newMonth,
newDay,
dt.hour,
dt.minute,
dt.second,
dt.millisecond,
dt.microsecond);
}
}
To get a set starting point at the start of a month, you can use DateTime along with the Jiffy package.
DateTime firstOfPreviousMonth
= DateTime.parse(
Jiffy().startOf(Units.MONTH)
.subtract(months: 1)
.format('yyyy-MM-dd'). //--> Jan 1 '2021-01-01 00:00:00.000'
);
var fifthOfMonth
= firstOfPreviousMonth.add(Duration(days: 4)); //--> Jan 5 '2021-01-05 00:00:00.000'
or
DateTime endOfPreviousMonth
= DateTime.parse(
Jiffy().endOf(Units.MONTH)
.subtract(months: 2)
.format('yyyy-MM-dd'). //--> Dec 30 '2020-12-31 00:00:00.000'
// endOf always goes to 30th
);
var previousMonth
= endOfPreviousMonth.add(Duration(days: 2)); //--> Jan 1 '2021-01-01 00:00:00.000'
DateFormat('MMMM yyyy')
.format(DateTime(DateTime.now().year, DateTime.now().month - 2)),
List<DateTime> newList = [];
DateFormat format = DateFormat("yyyy-MM-dd");
for (var i = 0; i < recents.length; i++) {
newList.add(format.parse(recents[i]['date'].toString()));
}
newList.sort(((a, b) => a.compareTo(b)));
var total = 0;
for (var i = 0; i < newList.length; i++) {
if (DateTime.now().difference(newList[i]).inDays < 30) {
print(newList[i]);
total++;
}
}
print(total);
You can use this to fetch the last 30 days.
In addition to Günter Zöchbauer Answer
var now = new DateTime.now();
String g = ('${now.year}/ ${now.month}/ ${now.day}');
print(g);

How to Subtract Days From Date in TypeScript

I would like to subtract days from the current date in TypeScript.
For example, if the current date is October 1st, 2017, I would like to subtract 1 day to get September 30th, 2017, or if I want to subtract 3 days I would get September 28th etc.
This is what I have so far, the result is I received December 31st, 1969. Which I assume means that tempDate.getDate() is returning zero, as in the Epoch of January 1, 1970.
This is my code, the goal is to return the previous working day.
protected generateLastWorkingDay(): Date {
var tempDate = new Date(Date.now());
var day = tempDate.getDay();
//** if Monday, return Friday
if (day == 1) {
tempDate = new Date(tempDate.getDate() - 3);
} else if (1 < day && day <= 6) {
tempDate = new Date(tempDate.getDate() - 1);
}
return tempDate;
}
getDate returns the date of the month (1-31), so creating a new Date from it treats that number as "milliseconds since epoch".
What you probably want is to use setDate to change the date as it automatically handled going backwards through months/years.
protected generateLastWorkingDay(): Date {
const lastWorkingDay = new Date();
while(!this.isWorkingDay(lastWorkingDay)) {
lastWorkingDay.setDate(lastWorkingDay.getDate()-1);
}
return lastWorkingDay;
}
private isWorkingDay(date: Date) {
const day = date.getDay();
const isWeekday = (day > 0 && day < 6);
return isWeekday; // && !isPublicHoliday?
}
This is how I did
let yesterday=new Date(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
let last3days=new Date(new Date().getTime() - (3 * 24 * 60 * 60 * 1000));
We need to minus (no_of_days) * 24 * 60 * 60 * 1000 from current date.
You can just
const current = new Date()
and then
const numberOfDaysToSubstract= 3;
const prior = new Date().setDate(current.getDate) - numberOfDaysToSubstract);
you can see an example of this here
https://codepen.io/Jeysoon/pen/poNZRwd?editors=1112

Verify a date in JavaScript

I need to do user validation of a date field, it should be in the format yyyyMMdd and should not be more than one year in the future. How would I go about doing this? Currently I only have a crude regexp which is insufficient.
function VerifyDate(source, args)
{
var regexp = /^([1-2]{1}[0-9]{1})\d{2}([0][1-9]|[1][0-2])([0][1-9]|[1-2][0-9]|[3][0-1])$/
var result = args.Value.match(regexp);
if(result) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
Take the regex to check the format only. You can stay simple:
^(\d{4})(\d{2})(\d{2})$
Then parse the date and check the range:
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var daysInMonth = function (y, m) {return 32-new Date(y, m, 32).getDate(); };
var ma = regexp.exec(args.Value);
if (ma && ma.length == 4 && ma[2] < 12 && ma[3] <= daysInMonth(ma[1], ma[2]))
{
var diff = new Date(ma[1], ma[2], ma[3]) - new Date();
args.IsValid = diff < 31536000000; // one year = 1000ms*60*60*24*365
}
}
new Date() don't throw an exception if month or day is out of range. It uses the internal MakeDay to calculate a date (see ECMAScript Language Specification section 15.9.3.1 and 15.9.1.13). To make sure that the date is valid in the function below, the input is converted to integers who is converted to a date, and then the parts of the date are compared to the integers.
Since date uses MakeDay, the calculation of maxDate works even if now is the leep day (xxxx0229 will be yyyy0301 where yyyy=xxxx+1)
function verifyDate(args)
{
var result=false,
match = args.Value.match(/^(\d{4})(\d{2})(\d{2})$/);
if (match && match.length === 4)
{
var year = parseInt(match[1],10),
month =parseInt(match[2],10) -1, // 0 = January
day = parseInt(match[3],10),
testDate= new Date(year,month,day),
now = new Date(),
maxDate = new Date(now.getFullYear() + 1, now.getMonth(), now. getDate()),
minDate = new Date(1800,0,1),
result = (
testDate.getFullYear() === year &&
testDate.getMonth() === month &&
testDate.getDate() === day &&
testDate >= minDate &&
testDate <= maxDate
);
}
args.IsValue = result;
return result;
}
The solution I finally went with is a combination of your answers, I used datejs which seems pretty nice. Here is my final validation function. For some reason the month seems to use a 0 based index so that's why it says -1 in the .set().
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var m = regexp.exec(args.Value);
if (m && m.length == 4) {
try {
var result = Date.today().set({ year: Number(m[1]), month: Number(m[2]-1), day: Number(m[3]) });
if (result < Date.today().add({ years: 1 })) {
args.IsValid = true;
}
}
catch (ex) {
}
}
}

Resources