I need one help.I am unable to compare the selected date with today's date using Angular.js or JavaScript.I am explaining my code below.
var today=new Date();
console.log('2 dates',today,$scope.date);
From the above console i am getting the output like below.
2 dates Fri Jun 03 2016 18:29:16 GMT+0530 (India Standard Time) 03-06-2016
if(today > new Date($scope.date.split("-").reverse().join(","))){
alert('Please select future delivery date');
}
Here i need suppose my selected date is 03-06-2016 and today's date is 03-06-2016 the alert prompt should not come.But in my case its not happening like this.This alert message is coming also if selected date is 03-06-2016. Here i need the alert message should come if selected date is more than today's date only.Please help me.
Months are zero-indexed when constructing Dates:
console.log(new Date(2016,06,03));
"2016-07-03T04:00:00.000Z" // you expected June, but got July.
Note also that that is set to midnight: any new Date() run during the same day will be greater than that value.
String manipulation of dates is risky and error-prone, which is why everyone's knee-jerking momentjs at you (it is in fact a very good library and worth using if you're doing much date manipulation).
At the least, you may want to consider using a less ambiguous date format in $scope.date, but if you're stuck with that, in this case, you need to subtract 1 from the month when constructing a Date from it:
// this sample code will only work correctly on June 3 2016 :)
var $scope = {
date: "03-06-2016", // I am assuming DD-MM-YYYY format here
tomorrow: "04-06-2016"
};
var today = new Date();
// test against today:
var dArr = $scope.date.split('-');
var testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today > testDate) {
console.log("today is greater than testDate.");
/* Note that anytime during today will be greater than the zero
o'clock constructed from $scope.date. If what you really want
is to alert only on the following day, then add 1 to the day
of $scope.date when converting it to a Date(). */
}
// now test against tomorrow:
dArr = $scope.tomorrow.split('-');
testDate = new Date(dArr[2],dArr[1]-1,dArr[0]);
if (today < testDate) {
console.log("today is less than (tomorrow's) testDate.");
}
Don't compare JavaScript dates using native < or > operators; install and use moment.js - it will handle all the difficulties for you:
if(moment(new Date()).isAfter(moment($scope.date, "MM-DD-YYYY"), 'day')) { ...
Convert to timestamp to compare it:
$scope.date = '2016-06-01';
var currentDate = new Date().valueOf();
var date = new Date($scope.date).valueOf();
if (currentDate > date) {
// something
}
It you use multi timezone, please convert both to a timezone.
Related
I'm using a component from AntUI library that renders the date picker.
What I want to do is to display Now and Tomorrow instead of today's/ tomorrow's dates.
Is there a specific momentJS format (I couldn't find any, so probably not) or a way to configure momentJS library that it will automatically display those values instead of those dates?
You could check if the date is between moment().startOf('day'); and moment().endOf('day'); and display Now or Tomorrow depending on the result
moment().isBetween(moment().startOf('day'), moment().endOf('day'));
would be Now (true) and
moment().add(1, 'day').isBetween(moment().startOf('day'), moment().endOf('day'));
and this would be Tomorrow (false)
Try this:
var today = moment().endOf('day')
var tomorrow = moment().add(1, 'day').endOf('day')
var date = new Date();
//Check Today's date
if (date < today)
alert('today')
if (date < tomorrow)
alert('tomorrow')
UPDATE
You can use this as well but it will show current time as well:
moment().calendar(); // Today at 10:37 AM
moment().add(1, 'days').calendar(); // Tomorrow at 10:37 AM
In my project, i use js code below to take date with date input only year and month:
var current_time = new Date(current);
with current data is something like this: "2017/04"
It work perfect on chrome but on IE 11, i get invalid date for current_time. Can your guys help to to take date form data which only has year and month like this on IE? Thankyou.
Dates should be formatted according RFC 2822 or ISO 8601 So if you use '-' instead of '/ it will work every where.
console.log(new Date("2017-04"))
if you want to still have your date with '/' you can do this
console.log(new Date("2017/04".replace(/\//g, "-")));
The format you are using is not a standard format of date. Non standard date formats cause problems on various browsers like IE, safari, etc.
Use this method. It will work on all IE as well
Run it on chrome and IE. Here in this snippet, it will give one month less since stack snippet is using a different library for date parsing.
var input = "2017/04"
var year = input.split("/")[0]
// indexing starts with 0
var month = parseInt(input.split("/")[1],10) -1
var date = new Date(year,month)
console.log(date)
This is what it will output on browsers including IE
Sat Apr 01 2017 00:00:00 GMT+0530 (India Standard Time)
In order to create the date by passing the month and year to dateObject you can do:
current = '2017/04';
current = current.split("/")
var date = new Date(current[0], current[1]);
// it will return the date object where date is set as the first day of the month
console.log(date)
which will give you the date object set to the first day of the month.
If you want to get the current month and year you can do:
var year = new Date().getFullYear();
var month = new Date().getMonth() + 1;
date = year + '/' + month;
console.log(date);
Why does javaScript allow creation of dates such as
invalidDate = new Date(2015,3,31);
Here I am trying to create a date with April 31st. Instead JavaScript creates a date as Fri May 01 2015 00:00:00. Should we validate the date before creating it?
There are scenarios when we try to parse invalid dates and it does the same thing. How should one parse the date correctly when the given date may not be valid?
var invalidDate = new Date(2015, 3, 31);
alert(invalidDate);
You can use the Date API to create the date and check the result:
function makeDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() !== year || d.getMonth() !== month)
throw new Error("Invalid date");
return d;
}
If the day is not a valid day for the given month, then the month will be adjusted; that's a feature of the Date API that allows easy "date math". If the above code notices that the input values have been corrected, it throws an exception.
Because there is no 31st April, so it's giving you the nearest valid date...
For clarity, as below, any integer above a valid date will roll over to the following month.
i.e. Date(2016,0,1) is 1st Jan 2016.
Date(2016,0,61) adds 60 days on to that date, which rolls past the 29th Feb 2016 and into March, thus..
Date(2016,0,61) = 1st March 2016
As a result, Date(2015,3,31) = 30th April 2015 plus one day = 1st May 2015
You can validate the date with a function like this:
function isValidDate(year, month, day) {
var m = month - 1; // Note: the month is 0-based
var d = new Date(year, m, day);
/*
For invalid dates, either the day or month gets changed:
2015-04-31 -> 2015-05-01
2015-02-29 -> 2015-03-01
2015-13-10 -> 2016-01-10
2016-00-10 -> 2015-12-10
*/
return d.getDate() == day && d.getMonth() == m;
}
In general, you should never trust user input. As a result, you should try to put them in a situation where they can not enter bad data. This can be done through validation or thought a User interface that only enables them to select valid dates.
You can look around SO for some examples on validating dates: Detecting an "invalid date" Date instance in JavaScript. If you are using a javascript framework they might already have something built into it as well.
As for why it works and "lets you do it", I would suspect that is because javascript's parse function calculates the "milliseconds elapsed since January 1, 1970, 00:00:00 UTC". The resulting milliseconds is then used and javascript represents that as the correct date.
I'm trying to convert today's date to an ISO standard string but with the fixed time of T00:00:00.000Z.
I can get as far as returning a ISO string of today's date and time:
var isoDate = new Date().toISOString();
// returns "2015-10-27T22:36:19.704Z"
But I wanted to know if it's possible to have a fixed time, so it should return:
"2015-10-27T00:00:00.000Z"
Is this possible?
Any help is appreciated. Thanks in advance!
To get the current UTC date at midnight:
var d = new Date();
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
var output = d.toISOString();
To get the current local date, with the time portion set to UTC midnight:
var d = new Date();
var ts = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
var output = new Date(ts).toISOString();
As for which to use, think through your requirements very carefully, The current UTC date and the local date may indeed be two different days.
For example, when it's midnight (00:00) October 27th in UTC, it's 8:00 PM on October 26th in New York.
Also, consider using moment.js, which makes operations like either of these much easier with the startOf('day') and .utc() functions.
I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.
With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?
function daysRemaining() {
var eventdate = moment([2015, 5, 14]);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.
Reference
So either change the month to 4 to reflect May or parse the date as an ISO 8601 string
function daysRemaining() {
var eventdate = moment("2015-05-14");
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
Just to add for anyone else that comes across this - there's actually a helper that does the phrasing etc for you:
https://momentjs.com/docs/#/displaying/to/
/* Retrieve a string describing the time from now to the provided date */
daysUntil: function(dateToCheckAgainst){
return new moment().to(moment(dateToCheckAgainst));
}
// Sample outputs
"in three months"
"in two months"
"in 25 days"
That's because months are zero indexed. So 5 is actually June ;)