Extract Values from incorrect Js Date Object? - javascript

I've build a function which checks if a date parts values are valid :
Bad value example :
new Date(2012,3,44) =
Mon May 14 2012 00:00:00 GMT+0300 (Jerusalem Daylight Time)
Here is the function ( its arguments are being sent by me separately !)
function isDate(year, month, day)
{
...
}
alert(isDate( 2001,2,29));
However , I have a problem.
If I have an invalid date object like : var t= new Date(2001,2,44) :
And I want to send it to my function , I need to extract its values.
How can I extract the 44 value + 2 value ?
t.getDate() //13
t.getMonth() //3 (days went from march to april)
any help ?

You can't extract the value 44 from the Date object, because it's not there.
When creating a Date object with out of range values, the values will be adjusted so that it becomes a valid date.
The components of a Date object always forms a valid date. If you want to check if the values are valid, you have to do that before creating the Date object, or use the Date object to check them:
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
// components were valid
}

Related

How to manipulate date in javascript

I'm having problem with manipulation of dates. I have a variable savedTime variable in localstorage wich contains this date:
Wed Aug 31 2016 16:31:30 GMT-0300 (Hora oficial do Brasil)
I need add 1 hour for this variable savedTime to check if passed 1 hour:
var savedTime = new Date(savedTime); //converts string to date object
var checkExpired = savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to savedTime
But on trying add 1 hour to this variable converting the string in a object, this (savedTime) returns:
1472675490000
What i expected is the string with + 1 hour:
Wed Aug 31 2016 17:31:30 GMT-0300 (Hora oficial do Brasil)
And compare dates to check if passed 1 hour
var currentDate = new Date();
if(currentDate > checkExpired) {
//passed 1 hour
}
instance.setHours() manipulates the instance. So you can do
d = new Date('Wed Aug 31 2016 16:31:30 GMT-0300');
d.setHours(d.getHours() + 1);
Now d contains the new datetime.
setHours will manipulate the current object and return it's new value. Instead of using the return value, just continue to use the object.
var savedTime = new Date(savedTime); //converts string to date object
savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to the savedTime
if (currentDate > savedTime) {
//passed 1 hour
}
Use .getTime()
if(currentDate.getTime() > checkExpired) {
//passed 1 hour
}
You are getting the value back in milliseconds from the 'epoch date' which is January first 1970.
If you want this in the correct format, you will need to parse this information out into that with some math / other Date object functions.
Here is the documentation to do that, it's very straightforward:
JS Date Formatting

How do I subtract two dates?

I have a date stored in a database as a string. It looks like this:
Tue Aug 23 2016 00:00:00 GMT-0500 (CDT)
I basically want to tell if today's date is before or after the date in the database.
The code below should sort of explain what I want. The problem is that after the difference variable doesn't return a number variable, which is what I need.
var expire = value.vaccines;
var today = new Date();
var difference = today-expire;
if(difference <= 0){
$(element).css({"color": "#0040ff"});
}
Any ideas on how to subtract these two dates and get a number value?
Assuming both your objects are Date
Although you only require the returned value in milliseconds, I've added the extra step of formatting the value.
Math.floor((today - expire) / (1000*60*60*24))
Taken from Here
You can just you can calculate the difference between the two Date objects and get the absolute value with Math.abs():
var today = new Date(),
expire = value.vaccines,
difference = Math.abs(today - expire); // difference in milliseconds
if (difference <= 0) {
$(element).css({
"color": "#0040ff"
});
}
Check that expire is a valid Date object.

Get the week day from a given date

I am writing my own calendar plugin but I am struggling to get the day of the week for a given date.
Lets say I have the year - 1905, the month - 4 and the day - 23. Is there any way at all that I could use this data - smash it together in a better format say YYYY/DD/MM and use this to calculate the day of the week - I was hoping to find some Gregorian calendar methods like in PHP but I am yet to find any.
Sorry if this has been asked before but I could only find questions using new Date for todays day of the week.
Construct a date object and ask it what day it is:
// Note months are zero indexed so May is 4, not 5
var d = new Date(1905, 4, 23).getDay(); // 2
Which you can turn into a function:
function getDay(y, m, d) {
var days = ['Sunday','Monday','Tuesday',
'Wednesday','Thursday','Friday','Saturday'];
var d = new Date(y, --m, d);
return d && days[d.getDay()];
}
// What day was 23 May, 1905?
console.log(getDay(1905,5,23)); // Tuesday
Edit
Note that these types of functions will convert two digit years into 20th century dates, e.g.
var d = new Date(5, 4, 23) // 23 May, 1905
and they don't check that the values are valid dates:
var d = new Date(5, 16, 23) // 23 May, 1906
If you don't want that, you have to construct the date differently and check the values:
// Create a generic date object
var d = new Date();
// Set the values for 23 May, 0005
// This way doesn't convert 5 to 1905
d.setFullYear(5, 4, 23);
// Check at least 2 values in the date are the same as the input
// The easiest to check are year and date
if (d.getFullYear() == 5 && d.getDate() == 23) {
console.log(d + 'is a valid date!');
}
You can create a separate function based on the above to create dates that returns either a date object or NaN if the values aren't valid (and honours two digit years).

Comparing Dates with different formats in Javascript

I'm attempting to compare 2 dates that have 2 different formats in Javascript.
The date from my database is 2013-04-21 (date1) and the date in the array prints out in the following format in my Chrome debugger: Sun Apr 21 2013 15:37:05 GMT-0400 (Eastern Daylight Time) (date2)
I'd like to compare only the date part and leave out the time: date1 == date2 is true.
How would I go about formatting the dates so I'd be able to compare them?
Any help is greatly appreciated.
y = date2.getFullYear();
m = date2.getMonth()+1;
m = (m<10)? ('0'+m) : m;
d = date2.getDate();
d2 = y+'-'+m+'-'+d;
if (date1 == d2) {
// do something
}
date1.toISOString().split("T")[0] == date2.toISOString().split("T")[0]
We have to go a little deeper here: we have to distinguishe between Strings storing date, and the Date object which can store dates and do computation with dates.
From your description i guess that date1 is acutally a string "2013-04-21" while date2 is already a Date object.
You could convert date1 to a date object:
date1AsObject = new Date("2013-04-21");
Then you could compute the difference between them:
diff = date2 - date1AsObject
the result will be in milliseconds.
or you could convert date2 to a string like
Crayon Violent suggested:
y = date2.getFullYear();
m = date2.getMonth()+1;
d = date2.getDate();
date2AsString = y+'-'+m+'-'+d;
then you can compare the two strings.

javascript Today() function

I'd like to determine if a given date object is the same day as the current day. Below is the psuedo code.
// date is a Date object
function (date)
{
if (date == Today())
alert('How are you today?');
else
alert('How were you last ' + date.toDateString() + '?');
}
How do I implement the Today() function? It doesn't have to be a function really, an equivalent solution will be just as good. Thanks.
[edit]
I forgot to mention. The current time (today) is local time and the date object that it will be compared with is server time, which can be anywhere in the world.
You can just compare the toDateString()s of the date string you're passing to a new Date() without any parameter passed to it (it will default to today).
// date is a Date object
function alertDateGreeting(date)
{
if (date.toDateString() == (new Date()).toDateString())
alert('How are you today?');
else
alert('How were you last ' + date.toDateString() + '?');
}
Use the following:
var today = new Date();
Keep in mind that the Javascript Date object is a timestamp despite its name. You will probably want to compare the individual fields for equality with getMonth(), getDate() and getFullYear(), as per the following sample:
<html>
<head>
</head>
<body>
<script language="javascript">
var today = new Date();
alert(
today.getFullYear() + "." +
(today.getMonth() + 1) + "." +
today.getDate()
);
</script>
</body>
</html>
This is an interesting question. First, you get the current datetime in JavaScript with
new Date()
However, comparing two dates is not really done with ==
Consider
> d = new Date(2011, 1, 1)
Tue Feb 01 2011 00:00:00 GMT-0800 (PST)
> d2 = new Date(2011, 1, 1)
Tue Feb 01 2011 00:00:00 GMT-0800 (PST)
> d == d2
false
But...
> d2 = new Date(2011, 1, 1).getTime()
1296547200000
> d = new Date(2011, 1, 1).getTime()
1296547200000
> d == d2
true
Because two date objects will be equal only if they are the exact same object. So when you compare dates, use getTime. If you are only concerned with the equality of dates and not date times, you have to do a little more work, but it is not so bad.
ADDENDUM:
The question asked for a way to talk about the current date.
Here you have two ways to go, at least.
From the datetime object, find the corresponding midnight time. There are algorithms for this, or you can use a package like date.js.
Hack it into a string: d.toISOString().substring(0,10). This is a ugly hack, and please, be careful about timezones!
There is no Today() method in javascript. You can use new Date() to get the current date.

Categories

Resources