how can i calculate the difference between two dates from the user input? - date

This is my code so far:
import datetime
from time import strptime
leapyear = 0
isValid = False
while not isValid:
in_date = input(" Please in put a year in the format dd/mm/yyyy ")
try:
d = strptime(in_date, '%d/%m/%Y')
isValid=True
except:
print ("This is not in the right format")
date = datetime.date.today().strftime("%d/""%m/""%Y")
in_date = in_date.split('/')
date = date.split('/')
in_date = [int(i) for i in in_date]
date = [int(i) for i in date]
date_f = [str(i) for i in date]
date_f = '/'.join(date_f)
in_date_f = [str(i) for i in in_date]
in_date_f = '/'.join(in_date_f)
newdate = []
in_date[0], in_date[2] = in_date[2], in_date[0]
date[0], date[2] = date[2], date[0]
z = "/"
if in_date > date:
newdate.insert((0),(in_date[2] % date[2]))
newdate.insert((1),(in_date[1] % date[1]))
newdate.insert((2),(in_date[0] % date[0]))
print("Current Date:", date_f)
print("you are:", newdate[2],"year(s)",newdate[1],"month(s) and",newdate[0],"days away from:",in_date_f)
else:
print("Please input a date thats higher than todays.")
At the moment i have taken today's date and then taken away that from the user input date which has to be higher than the current date. but this gives the wrong answer because it hasnt taken in the fact of the days in a month the and the months in a year.
how would i go about doing that?

datetime objects are subtractable and comparable, so there is no problem in doing:
userDate = strptime(in_date, '%d/%m/%Y')
if userDate > datetime.datetime.today():
# ...
or
if userDate.date() > datetime.datetime.today().date():
# ....
or to calculate the difference:
diff = userDate - datetime.datetime.today()

Related

When I filter by date using .setHours to remove the time, the time is then lost in the filter [duplicate]

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.
The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.
The ==, !=, ===, and !== operators require you to use date.getTime() as in
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
For the curious, date.getTime() documentation:
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
Compare < and > just as usual, but anything involving == or === should use a + prefix. Like so:
const x = new Date('2013-05-23');
const y = new Date('2013-05-23');
// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y); // true
console.log('x >= y', x >= y); // true
console.log('x === y', x === y); // false, oops!
// anything involving '==' or '===' should use the '+' prefix
// it will then compare the dates' millisecond values
console.log('+x === +y', +x === +y); // true
The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
-1 if a < b
0 if a = b
1 if a > b
NaN if a or b is an illegal date
dates.inRange (d,start,end)
Returns a boolean or NaN:
true if d is between the start and end (inclusive)
false if d is before start or after end.
NaN if one or more of the dates are illegal.
dates.convert
Used by the other functions to convert their input to a date object. The input can be
a date-object : The input is returned as is.
an array: Interpreted as [year,month,day]. NOTE month is 0-11.
a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.
.
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
The relational operators < <= > >= can be used to compare JavaScript dates:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 < d2; // true
d1 <= d2; // true
d1 > d2; // false
d1 >= d2; // false
However, the equality operators == != === !== cannot be used to compare (the value of) dates because:
Two distinct objects are never equal for either strict or abstract comparisons.
An expression comparing Objects is only true if the operands reference the same Object.
You can compare the value of dates for equality using any of these methods:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
* note: d1 == d2 returns false as described above
*/
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1) == Number(d2); // true
+d1 == +d2; // true
Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.
By far the easiest method is to subtract one date from the other and compare the result.
var oDateOne = new Date();
var oDateTwo = new Date();
alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);
Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...
Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...
1. you have 2 string values you get from an input and you'd like to compare them, they are as below:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:
date1 = new Date(date1);
date2 = new Date(date2);
3. Now simply compare them, using the > < >= <=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
Compare day only (ignoring time component):
Date.prototype.sameDay = function(d) {
return this.getFullYear() === d.getFullYear()
&& this.getDate() === d.getDate()
&& this.getMonth() === d.getMonth();
}
Usage:
if(date1.sameDay(date2)) {
// highlight day on calendar or something else clever
}
I no longer recommend modifying the prototype of built-in objects. Try this instead:
function isSameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth();
}
console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.
e.g.
> (new Date('Jan 15 2021 01:39:53 Z')).getDate() // Jan 15 in UTC
14 // Returns "14" because I'm in GMT-08
what format?
If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true
Note - Compare Only Date Part:
When we compare two date in javascript. It takes hours, minutes and seconds also into consideration.. So If we only need to compare date only, this is the approach:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
Now: if date1.valueOf()> date2.valueOf() will work like a charm.
The simple way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
SHORT ANSWER
Here is a function that return {boolean} if the from dateTime > to dateTime Demo in action
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
function isFromBiggerThanTo(dtmfrom, dtmto){
return new Date(dtmfrom).getTime() >= new Date(dtmto).getTime() ;
}
console.log(isFromBiggerThanTo(from, to)); //true
Explanation
jsFiddle
var date_one = '2013-07-29 01:50:00',
date_two = '2013-07-29 02:50:00';
//getTime() returns the number of milliseconds since 01.01.1970.
var timeStamp_date_one = new Date(date_one).getTime() ; //1375077000000
console.log(typeof timeStamp_date_one);//number
var timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000
console.log(typeof timeStamp_date_two);//number
since you are now having both datetime in number type
you can compare them with any Comparison operations
( >, < ,= ,!= ,== ,!== ,>= AND <=)
Then
if you are familiar with C# Custom Date and Time Format String this library should do the exact same thing and help you format your date and time dtmFRM whether you are passing in date time string or unix format
Usage
var myDateTime = new dtmFRM();
alert(myDateTime.ToString(1375077000000, "MM/dd/yyyy hh:mm:ss ampm"));
//07/29/2013 01:50:00 AM
alert(myDateTime.ToString(1375077000000,"the year is yyyy and the day is dddd"));
//this year is 2013 and the day is Monday
alert(myDateTime.ToString('1/21/2014', "this month is MMMM and the day is dd"));
//this month is january and the day is 21
DEMO
all you have to do is passing any of these format pacified in the library js file
You can use this code:
var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');
var firstDate=new Date();
firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);
var secondDate=new Date();
secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);
if (firstDate > secondDate)
{
alert("First Date is greater than Second Date");
}
else
{
alert("Second Date is greater than First Date");
}
And also check the MDN article for the Date class.
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
BEWARE THE TIMEZONE
A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy functions for translating to and from strings in the "local" timezone. If you want to work with dates using date objects, as everyone here is doing, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, particularly when you create your midnight UTC Date object.
Most of the time, you will want your date to reflect the timezone of the user. Click if today is your birthday. Users in NZ and US click at the same time and get different dates. In that case, do this...
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
Sometimes, international comparability trumps local accuracy. In that case, do this...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));
Now you can directly compare your date objects as the other answers suggest.
Having taken care to manage timezone when you create, you also need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
And totally avoid everything else, especially...
getYear(),getMonth(),getDate()
Via Moment.js
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
The method returns 1 if dateTimeA is greater than dateTimeB
The method returns 0 if dateTimeA equals dateTimeB
The method returns -1 if dateTimeA is less than dateTimeB
Just to add yet another possibility to the many existing options, you could try:
if (date1.valueOf()==date2.valueOf()) .....
...which seems to work for me. Of course you do have to ensure that both dates are not undefined...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
This way we can ensure that a positive comparison is made if both are undefined also, or...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
...if you prefer them not to be equal.
If following is your date format, you can use this code:
var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
//...
}
It will check whether 20121121 number is bigger than 20121103 or not.
Subtract two date get the difference in millisecond, if you get 0 it's the same date
function areSameDate(d1, d2){
return d1 - d2 === 0
}
Say you got the date objects A and B, get their EPOC time value, then subtract to get the difference in milliseconds.
var diff = +A - +B;
That's all.
One way to compare two dates is to use the dates.js library.
The Date.compare(Date date1, Date date2) method that returns a number which means the one of following result:
-1 = date1 is less than date2.
0 = values are equal.
1 = date1 is greater than date2.
Performance
Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
Conclusions
solutions d1==d2 (D) and d1===d2 (E) are fastest for all browsers
solution getTime (A) is faster than valueOf (B) (both are medium fast)
solutions F,L,N are slowest for all browsers
Details
In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE
function A(d1,d2) {
return d1.getTime() == d2.getTime();
}
function B(d1,d2) {
return d1.valueOf() == d2.valueOf();
}
function C(d1,d2) {
return Number(d1) == Number(d2);
}
function D(d1,d2) {
return d1 == d2;
}
function E(d1,d2) {
return d1 === d2;
}
function F(d1,d2) {
return (!(d1>d2 || d2>d1));
}
function G(d1,d2) {
return d1*1 == d2*1;
}
function H(d1,d2) {
return +d1 == +d2;
}
function I(d1,d2) {
return !(+d1 - +d2);
}
function J(d1,d2) {
return !(d1 - d2);
}
function K(d1,d2) {
return d1 - d2 == 0;
}
function L(d1,d2) {
return !((d1>d2)-(d1<d2));
}
function M(d1,d2) {
return d1.getFullYear() === d2.getFullYear()
&& d1.getDate() === d2.getDate()
&& d1.getMonth() === d2.getMonth();
}
function N(d1,d2) {
return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );
}
// TEST
let past= new Date('2002-12-24'); // past
let now= new Date('2020-02-26'); // now
console.log('Code d1>d2 d1<d2 d1=d2')
var log = (l,f) => console.log(`${l} ${f(now,past)} ${f(past,now)} ${f(now,now)}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
p {color: red}
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
Results for chrome
In order to create dates from free text in JavaScript you need to parse it into the Date object.
You could use Date.parse() which takes free text and tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.
Once you have a date, as other people have pointed out, you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function
var input_date="2015/04/22 11:12 AM";
var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime = new Date(Date.parse(input_date));
if (inputDateTime <= currentDateTime){
//Do something...
}
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours ;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours+":"+minutes+ ' ' + ampm;
return date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
(date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
date.getDate()) + " " + strTime;
}
An Improved version of the code posted by "some"
/* Compare the current date against another date.
*
* #param b {Date} the other date
* #returns -1 : if this < b
* 0 : if this === b
* 1 : if this > b
* NaN : if a or b is an illegal date
*/
Date.prototype.compare = function(b) {
if (b.constructor !== Date) {
throw "invalid_date";
}
return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ?
(this>b)-(this<b) : NaN
);
};
usage:
var a = new Date(2011, 1-1, 1);
var b = new Date(2011, 1-1, 1);
var c = new Date(2011, 1-1, 31);
var d = new Date(2011, 1-1, 31);
assertEquals( 0, a.compare(b));
assertEquals( 0, b.compare(a));
assertEquals(-1, a.compare(c));
assertEquals( 1, c.compare(a));
I usually store Dates as timestamps(Number) in databases.
When I need to compare, I simply compare among those timestamps or
convert it to Date Object and then compare with > <if necessary.
Note that == or === does not work properly unless your variables are references of the same Date Object.
Convert those Date objects to timestamp(number) first and then compare equality of them.
Date to Timestamp
var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp
Timestamp to Date
var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);
Before comparing the Dates object, try setting both of their milliseconds to zero like Date.setMilliseconds(0);.
In some cases where the Date object is dynamically created in javascript, if you keep printing the Date.getTime(), you'll see the milliseconds changing, which will prevent the equality of both dates.
Let's suppose that you deal with this 2014[:-/.]06[:-/.]06 or this 06[:-/.]06[:-/.]2014 date format, then you may compare dates this way
var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';
parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false
As you can see, we strip separator(s) and then compare integers.
My simple answer for this question
checkDisabled(date) {
const today = new Date()
const newDate = new Date(date._d)
if (today.getTime() > newDate.getTime()) {
return true
}
return false
}
If both of your dates come in the format "YYYY-MM-DD", you can skip the Date object and compare strings directly.
This works because of how the strings are compared in JS
let date1 = '2022-12-13';
let date2 = '2022-02-13';
console.log(`${date1} > ${date2}`, date1 > date2);
console.log(`${date1} < ${date2}`, date1 < date2);
console.log(`${date1} == ${date2}`, date1 == date2);

Apparently identical dates fail test for equivalency [duplicate]

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.
The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.
The ==, !=, ===, and !== operators require you to use date.getTime() as in
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
For the curious, date.getTime() documentation:
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
Compare < and > just as usual, but anything involving == or === should use a + prefix. Like so:
const x = new Date('2013-05-23');
const y = new Date('2013-05-23');
// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y); // true
console.log('x >= y', x >= y); // true
console.log('x === y', x === y); // false, oops!
// anything involving '==' or '===' should use the '+' prefix
// it will then compare the dates' millisecond values
console.log('+x === +y', +x === +y); // true
The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
-1 if a < b
0 if a = b
1 if a > b
NaN if a or b is an illegal date
dates.inRange (d,start,end)
Returns a boolean or NaN:
true if d is between the start and end (inclusive)
false if d is before start or after end.
NaN if one or more of the dates are illegal.
dates.convert
Used by the other functions to convert their input to a date object. The input can be
a date-object : The input is returned as is.
an array: Interpreted as [year,month,day]. NOTE month is 0-11.
a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.
.
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
The relational operators < <= > >= can be used to compare JavaScript dates:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 < d2; // true
d1 <= d2; // true
d1 > d2; // false
d1 >= d2; // false
However, the equality operators == != === !== cannot be used to compare (the value of) dates because:
Two distinct objects are never equal for either strict or abstract comparisons.
An expression comparing Objects is only true if the operands reference the same Object.
You can compare the value of dates for equality using any of these methods:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
* note: d1 == d2 returns false as described above
*/
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1) == Number(d2); // true
+d1 == +d2; // true
Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.
By far the easiest method is to subtract one date from the other and compare the result.
var oDateOne = new Date();
var oDateTwo = new Date();
alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);
Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...
Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...
1. you have 2 string values you get from an input and you'd like to compare them, they are as below:
var date1 = '01/12/2018';
var date2 = '12/12/2018';
2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:
date1 = new Date(date1);
date2 = new Date(date2);
3. Now simply compare them, using the > < >= <=
date1 > date2; //false
date1 < date2; //true
date1 >= date2; //false
date1 <= date2; //true
Compare day only (ignoring time component):
Date.prototype.sameDay = function(d) {
return this.getFullYear() === d.getFullYear()
&& this.getDate() === d.getDate()
&& this.getMonth() === d.getMonth();
}
Usage:
if(date1.sameDay(date2)) {
// highlight day on calendar or something else clever
}
I no longer recommend modifying the prototype of built-in objects. Try this instead:
function isSameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth();
}
console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.
e.g.
> (new Date('Jan 15 2021 01:39:53 Z')).getDate() // Jan 15 in UTC
14 // Returns "14" because I'm in GMT-08
what format?
If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true
Note - Compare Only Date Part:
When we compare two date in javascript. It takes hours, minutes and seconds also into consideration.. So If we only need to compare date only, this is the approach:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
Now: if date1.valueOf()> date2.valueOf() will work like a charm.
The simple way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
SHORT ANSWER
Here is a function that return {boolean} if the from dateTime > to dateTime Demo in action
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
function isFromBiggerThanTo(dtmfrom, dtmto){
return new Date(dtmfrom).getTime() >= new Date(dtmto).getTime() ;
}
console.log(isFromBiggerThanTo(from, to)); //true
Explanation
jsFiddle
var date_one = '2013-07-29 01:50:00',
date_two = '2013-07-29 02:50:00';
//getTime() returns the number of milliseconds since 01.01.1970.
var timeStamp_date_one = new Date(date_one).getTime() ; //1375077000000
console.log(typeof timeStamp_date_one);//number
var timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000
console.log(typeof timeStamp_date_two);//number
since you are now having both datetime in number type
you can compare them with any Comparison operations
( >, < ,= ,!= ,== ,!== ,>= AND <=)
Then
if you are familiar with C# Custom Date and Time Format String this library should do the exact same thing and help you format your date and time dtmFRM whether you are passing in date time string or unix format
Usage
var myDateTime = new dtmFRM();
alert(myDateTime.ToString(1375077000000, "MM/dd/yyyy hh:mm:ss ampm"));
//07/29/2013 01:50:00 AM
alert(myDateTime.ToString(1375077000000,"the year is yyyy and the day is dddd"));
//this year is 2013 and the day is Monday
alert(myDateTime.ToString('1/21/2014', "this month is MMMM and the day is dd"));
//this month is january and the day is 21
DEMO
all you have to do is passing any of these format pacified in the library js file
You can use this code:
var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');
var firstDate=new Date();
firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);
var secondDate=new Date();
secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);
if (firstDate > secondDate)
{
alert("First Date is greater than Second Date");
}
else
{
alert("Second Date is greater than First Date");
}
And also check the MDN article for the Date class.
function datesEqual(a, b)
{
return (!(a>b || b>a))
}
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
BEWARE THE TIMEZONE
A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy functions for translating to and from strings in the "local" timezone. If you want to work with dates using date objects, as everyone here is doing, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, particularly when you create your midnight UTC Date object.
Most of the time, you will want your date to reflect the timezone of the user. Click if today is your birthday. Users in NZ and US click at the same time and get different dates. In that case, do this...
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
Sometimes, international comparability trumps local accuracy. In that case, do this...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));
Now you can directly compare your date objects as the other answers suggest.
Having taken care to manage timezone when you create, you also need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
And totally avoid everything else, especially...
getYear(),getMonth(),getDate()
Via Moment.js
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
The method returns 1 if dateTimeA is greater than dateTimeB
The method returns 0 if dateTimeA equals dateTimeB
The method returns -1 if dateTimeA is less than dateTimeB
Just to add yet another possibility to the many existing options, you could try:
if (date1.valueOf()==date2.valueOf()) .....
...which seems to work for me. Of course you do have to ensure that both dates are not undefined...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
This way we can ensure that a positive comparison is made if both are undefined also, or...
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
...if you prefer them not to be equal.
If following is your date format, you can use this code:
var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
//...
}
It will check whether 20121121 number is bigger than 20121103 or not.
Subtract two date get the difference in millisecond, if you get 0 it's the same date
function areSameDate(d1, d2){
return d1 - d2 === 0
}
Say you got the date objects A and B, get their EPOC time value, then subtract to get the difference in milliseconds.
var diff = +A - +B;
That's all.
One way to compare two dates is to use the dates.js library.
The Date.compare(Date date1, Date date2) method that returns a number which means the one of following result:
-1 = date1 is less than date2.
0 = values are equal.
1 = date1 is greater than date2.
Performance
Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
Conclusions
solutions d1==d2 (D) and d1===d2 (E) are fastest for all browsers
solution getTime (A) is faster than valueOf (B) (both are medium fast)
solutions F,L,N are slowest for all browsers
Details
In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE
function A(d1,d2) {
return d1.getTime() == d2.getTime();
}
function B(d1,d2) {
return d1.valueOf() == d2.valueOf();
}
function C(d1,d2) {
return Number(d1) == Number(d2);
}
function D(d1,d2) {
return d1 == d2;
}
function E(d1,d2) {
return d1 === d2;
}
function F(d1,d2) {
return (!(d1>d2 || d2>d1));
}
function G(d1,d2) {
return d1*1 == d2*1;
}
function H(d1,d2) {
return +d1 == +d2;
}
function I(d1,d2) {
return !(+d1 - +d2);
}
function J(d1,d2) {
return !(d1 - d2);
}
function K(d1,d2) {
return d1 - d2 == 0;
}
function L(d1,d2) {
return !((d1>d2)-(d1<d2));
}
function M(d1,d2) {
return d1.getFullYear() === d2.getFullYear()
&& d1.getDate() === d2.getDate()
&& d1.getMonth() === d2.getMonth();
}
function N(d1,d2) {
return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );
}
// TEST
let past= new Date('2002-12-24'); // past
let now= new Date('2020-02-26'); // now
console.log('Code d1>d2 d1<d2 d1=d2')
var log = (l,f) => console.log(`${l} ${f(now,past)} ${f(past,now)} ${f(now,now)}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
p {color: red}
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
Results for chrome
In order to create dates from free text in JavaScript you need to parse it into the Date object.
You could use Date.parse() which takes free text and tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.
Once you have a date, as other people have pointed out, you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function
var input_date="2015/04/22 11:12 AM";
var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime = new Date(Date.parse(input_date));
if (inputDateTime <= currentDateTime){
//Do something...
}
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours ;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours+":"+minutes+ ' ' + ampm;
return date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
(date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
date.getDate()) + " " + strTime;
}
An Improved version of the code posted by "some"
/* Compare the current date against another date.
*
* #param b {Date} the other date
* #returns -1 : if this < b
* 0 : if this === b
* 1 : if this > b
* NaN : if a or b is an illegal date
*/
Date.prototype.compare = function(b) {
if (b.constructor !== Date) {
throw "invalid_date";
}
return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ?
(this>b)-(this<b) : NaN
);
};
usage:
var a = new Date(2011, 1-1, 1);
var b = new Date(2011, 1-1, 1);
var c = new Date(2011, 1-1, 31);
var d = new Date(2011, 1-1, 31);
assertEquals( 0, a.compare(b));
assertEquals( 0, b.compare(a));
assertEquals(-1, a.compare(c));
assertEquals( 1, c.compare(a));
I usually store Dates as timestamps(Number) in databases.
When I need to compare, I simply compare among those timestamps or
convert it to Date Object and then compare with > <if necessary.
Note that == or === does not work properly unless your variables are references of the same Date Object.
Convert those Date objects to timestamp(number) first and then compare equality of them.
Date to Timestamp
var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp
Timestamp to Date
var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);
Before comparing the Dates object, try setting both of their milliseconds to zero like Date.setMilliseconds(0);.
In some cases where the Date object is dynamically created in javascript, if you keep printing the Date.getTime(), you'll see the milliseconds changing, which will prevent the equality of both dates.
Let's suppose that you deal with this 2014[:-/.]06[:-/.]06 or this 06[:-/.]06[:-/.]2014 date format, then you may compare dates this way
var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';
parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false
As you can see, we strip separator(s) and then compare integers.
My simple answer for this question
checkDisabled(date) {
const today = new Date()
const newDate = new Date(date._d)
if (today.getTime() > newDate.getTime()) {
return true
}
return false
}
If both of your dates come in the format "YYYY-MM-DD", you can skip the Date object and compare strings directly.
This works because of how the strings are compared in JS
let date1 = '2022-12-13';
let date2 = '2022-02-13';
console.log(`${date1} > ${date2}`, date1 > date2);
console.log(`${date1} < ${date2}`, date1 < date2);
console.log(`${date1} == ${date2}`, date1 == date2);

presenting Unix Timestamps with Swift

Using a current timestamp and a given timestamp, what is the best way to present them on a page? If the given timestamp represents "yesterday" the presentation should say yesterday. if the given timestamp was minutes or hours ago, it should only include how many. etc. is it best to subtract one from the other and evaluate what the difference means or is there a built-in library or framework that can be used? so far I am working with the following playground:
let ts = 1499299978.149724
let current_ts: Double
let date = NSDate(timeIntervalSince1970: ts)
let dayTimePeriodFormatter = DateFormatter()
let totalFormat = "MMM dd YYYY hh:mm a" //just for reference
dayTimePeriodFormatter.dateFormat = "hh:mm a" //add to this as desired
let dateString = dayTimePeriodFormatter.string(from: date as Date)
this should get you started:
let midnight = startOfToday.timeIntervalSince1970
let secondsInADay = 86400.0
if ts > midnight {
print ("today")
code
} else if ts > midnight - secondsInADay {
print ("yesterday")
code
} else if ts > midnight - secondsInADay - secondsInADay {
print ("2 days ago")
code
} else if ts > midnight - secondsInADay * 3 {
print ("3 days ago")
code
}
inside the "today" block you can use a similar process to check for seconds ago, minutes ago, else then subtract the ts from the current ts then divide by 60 accordingly to get the number you need

Constructing NSDate using DateComponent gives inconsistent results

I've created an extension for NSDate which removes the time component to allow equality checks for NSDate based on date alone. I have achieved this by taking the original NSDate object, obtaining the day, month and year using the DateComponent class and then constructing a new NSDate using the information obtained. Although the NSDate objects obtained look correct when printed to the console (i.e. timestamp is 00:00:00) and using the NSDate.compare function on two identical dates returns NSComparisonResult.OrderedSame, if you deconstruct them using DateComponent once more, some of them have the hour set to 1. This appears to be a random event with this error being present about 55% of the time. Forcing the hour, minute and second properties of DateComponent to zero before constructing the new NSDate rather than assuming they will default to these values does not rectify the situation. Ensuring the timezone is set helps a little but again does not fix it.
I am guessing there may be a rounding error somewhere (possibly in my test code), I've fluffed the conversion or there is a Swift bug but would appreciate comments. Code and output from a unit test below.
Code as follows:
extension NSDate {
// creates a NSDate object with time set to 00:00:00 which allows equality checks on dates alone
var asDateOnly: NSDate {
get {
let userCalendar = NSCalendar.currentCalendar()
let dayMonthYearUnits: NSCalendarUnit = .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear
var dateComponents = userCalendar.components(dayMonthYearUnits, fromDate: self)
dateComponents.timeZone = NSTimeZone(name: "GMT")
// dateComponents.hour = 0
// dateComponents.minute = 0
// dateComponents.second = 0
let result = userCalendar.dateFromComponents(dateComponents)!
return result
}
}
Test func:
func testRemovingTimeComponentFromRandomNSDateObjectsAlwaysResultsInNSDateSetToMidnight() {
var dates = [NSDate]()
let dateRange = NSDate.timeIntervalSinceReferenceDate()
for var i = 0; i < 30; i++ {
let randomTimeInterval = Double(arc4random_uniform(UInt32(dateRange)))
let date = NSDate(timeIntervalSinceReferenceDate: randomTimeInterval).asDateOnly
let dateStrippedOfTime = date.asDateOnly
// get the hour, minute and second components from the stripped date
let userCalendar = NSCalendar.currentCalendar()
var hourMinuteSecondUnits: NSCalendarUnit = .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond
var dateComponents = userCalendar.components(hourMinuteSecondUnits, fromDate: dateStrippedOfTime)
dateComponents.timeZone = NSTimeZone(name: "GMT")
XCTAssertTrue((dateComponents.hour == 0) && (dateComponents.minute == 0) && (dateComponents.second == 0), "Time components were not set to zero - \nNSDate: \(date) \nIndex: \(i) H: \(dateComponents.hour) M: \(dateComponents.minute) S: \(dateComponents.second)")
}
}
Output:
testRemovingTimeComponentFromRandomNSDateObjectsAlwaysResultsInNSDateSetToMidnight] : XCTAssertTrue failed - Time components were not set to zero -
NSDate: 2009-06-19 00:00:00 +0000
Index: 29 H: 1 M: 0 S: 0
I am sure that your test dates you created randomly will contain dates that live in DST (Daylight Saving Time) hence the 1 hour offset — indeed a clock would show 0:00.
Your code is anyway overly complicated and not timezone aware, as you overwrite it.
Preparation: create to dates on the same day with 5 hours apart.
var d1 = NSDate()
let cal = NSCalendar.currentCalendar()
d1 = cal.dateBySettingUnit(NSCalendarUnit.CalendarUnitHour, value: 12, ofDate: d1, options: nil)!
d1 = cal.dateBySettingUnit(NSCalendarUnit.CalendarUnitMinute, value: 0, ofDate: d1, options: nil)!
d1 is noon at users location today.
let comps = NSDateComponents()
comps.hour = 5;
var d2 = cal.dateByAddingComponents(comps, toDate: d1, options: nil)!
d2 five hours later
Comparison: This comparison will yield equal, as the dates are on the same day
let b = cal.compareDate(d1, toDate: d2, toUnitGranularity: NSCalendarUnit.CalendarUnitDay)
if b == .OrderedSame {
println("equal")
} else {
println("not equal")
}
The following will yield non equal, as the dates are not in the same hour
let b = cal.compareDate(d1, toDate: d2, toUnitGranularity: NSCalendarUnit.CalendarUnitHour)
if b == .OrderedSame {
println("equal")
} else {
println("not equal")
}
Display the dates with a date formatter, as it will take DST and timezones in account.

Passing an object of a class to a method in the class

I wrote a simple date class for practice but I can't seem to pass the objects in the class to the methods within the class. The class is supposed to be able to accept test dates, correct them if they are out of range and then print the correct date. Here is the code
class Date:
month = int
day = int
year = int
def setDate(self, month, day, year)
HIGH_MONTH = 12
HIGHEST_DAYS = ['none',31,29,31,30,31,30,31,31,30,31,30,31]
if month > HIGH_MONTH:
month = HIGH_MONTH
elif month < 1:
month = 1
else:
month = month
if day > HIGHEST_DAYS[month]:
day = HIGHEST_DAYS[month]
elif day < 1:
day = 1
else:
day = day
def showDate(self):
print 'Date:',month,'/',day,'/',year
#These are my tests
birthday=Date()
graduation=Date()
birthday.month=6
birthday.day=24
birthday.year=1984
graduation.setDate(5,36,2016)
birthday.showDate()
graduation.showDate()
What I get is a NameError: global name 'month' is not defined
In order for you to use a "global" variable in your class, assign the variables to self.variable_name as such:
class Date:
month = int
day = int
year = int
def setDate(self, month, day, year):
HIGH_MONTH = 12
HIGHEST_DAYS = [None,31,29,31,30,31,30,31,31,30,31,30,31]
if month > HIGH_MONTH:
month = HIGH_MONTH
elif month < 1:
month = 1
else:
month = month
if day > HIGHEST_DAYS[month]:
day = HIGHEST_DAYS[month]
elif day < 1:
day = 1
else:
day = day
self.year = year
self.month = month
self.day = day
def showDate(self):
print 'Date:',self.month,'/',self.day,'/',self.year
>>> birthday=Date()
>>> graduation=Date()
>>> birthday.month=6
>>> birthday.day=24
>>> birthday.year=1984
>>> graduation.setDate(5,36,2016)
>>> birthday.showDate()
Date: 6 / 24 / 1984
>>> graduation.showDate()
Date: 5 / 31 / 2016
>>>