I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:
if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)
The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.
Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.
var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);
If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:
var momentdate = moment(date);
if (momentdate.isAfter(momentdate.add(1, 'year') ||
momentdate.isBefore(momentdate.startOf('day')) {
// Invalid date?
}
Hope this helps.
Related
Suppose I have ISO Date inside an object as:
const dataCreated = {"readDetail":'2020-09-17 14:23:26.978Z'}
Is it possible to I get all date from created date till todays date.
Expected O/P ->assunming current date is jan 2021 :
['2020-09-17','2020-10-17','2020-11-17','2020-12-17','2021-01-17']
I tried different searches but was unable to get find anything related to it. If anyone has any solution or in someway can guide me that would be really helpful. If any further information needed please let me know.
What you want to do is just fill your array while looping over the dates. And with each loop add one month to your original date.
Note that you have to to create a new Instance of Date before saving it in your array since JavaScript saves references.
function getDates() {
var date = new Date("2020-09-17 14:23:26.978Z");
var now = new Date();
var datearray = [new Date(date)];
while(date.setMonth(date.getMonth() + 1) < now) {
datearray.push(new Date(date));
}
console.log(datearray);
}
Contrary to your expected output I'm saving Date Objects in the array. This has the advantage of giving you more opportunities when working with the Array elements afterwards. This could easily be changed though by changing the line where the Date object is pushed to the array.
I am trying to read all dates in a table and see if those dates are old dates than current date time and if those are old dates then highlight those dates with some color.
Here is my Javascript code
$(".ticket-gird-td-duedate").each(function(i, e) {
debugger;
var dueDateAsString = $(e).text();
console.log(dueDateAsString);
var dueDate = new Date(dueDateAsString);
var currentdate = new Date();
if (dueDate < currentdate) {
//mark date in red color
console.log("I need to change color for this date as this is past date" + dueDate);
}
});
Problem here is dueDateAsString comes as "07/10/2017 18:30 PM"
And when I am doing
new Date("07/10/2017 18:30 PM")
it fails with invalid date error
Invalid Date
How can I convert my string date to Javascript date and proceed to compare it with current date?
That isn't a valid date, as you either have 24hr format or AM|PM 12hr format.
This works:
new Date('07/10/2017 18:30'); // No 'PM' after the 24hr time
Also note that JS dates are mutable, so todayDate and check will hold the same date value, but check will be a number.
You call this one first
todayDate.setDate(todayDate.getDate() - 5);
It will update todayDate to 5 days ago. Then you just assign it to check or you todayDate further.
var check = todayDate;
Hope this helps.
You can do this by using moment.js library (yet another terrific way to achieve date parsing).
Moment.Js library is freely available. You can use either a minified or full version of this library as you require. In this
library all the operations are performed on a moment object so the
date or time is stored in this library as a moment object only. So
this moment object is the core of this entire library. You can find
this library at Moment.js site's home page.
Add momentjs library reference into your project - https://momentjs.com/downloads/moment.js
updated code with moment.js would be:
var todayDate = new moment().format("MM/DD/YYYY h:mm:ss a");
var yesterday = todayDate.toLocaleString();
var check = moment(todayDate, "MM/DD/YYYY h:mm:ss a").add('days', -5);
alert("Your Old Date is- " + todayDate);
alert(check);
alert("Your Old Date is- " + yesterday);
JavaScript fiddle
I want to get start and enddates for upcoming 4 weeks(only weekdays).
Suppose today's date is 2015-12-01 then the result should be as below
Week0 will have StartDate = 2015-11-30 and EndDate = 2015-12-04
Week1 will have StartDate = 2015-12-07 and EndDate = 2015-12-11
Week2 will have StartDate = 2015-12-14 and EndDate = 2015-12-18
Week3 will have StartDate = 2015-12-21 and EndDate = 2015-12-25
Here date of Week0 should be calculated from current date.
Try the moment library. It's pretty easy to use, so you should be able to figure out quickly, how to do this.
var date = moment(yourdate);
// iterate by date.add(1, "week")
var start = date.clone().startOf('week');
var end = date.clone().endOf('week');
//use .format('YYYY-MM-DD'); to print out
Here is how you would use the Moment.js library (as mentioned in the comments) to achieve the output you desire. It's quite easy by using the built in functions (to see the result, hit F12 on your keyboard or open the console some other way)
var weeks = 4;
for (var i = 0 ; i < weeks ; i++) {
var start = moment().startOf('isoweek').add(i, 'weeks');
var end = start.clone().add(4, 'days');
console.log("Week%d will have StartDate = %s and EndDate = %s", i, start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
}
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Couple simple built in functions at work here, namely:
moment, which is an instance of the moment class - essentially a datetime string.
startOf, pretty self explanatory, finds the exact datetime of when (in this case) the start of the week was
add, which adds a certain amount of x i.e. days, weeks, months etc. to the moment instance
clone, a necessary step which clones the original moment to prevent it from being modified by the end variable.
and format, pretty obvious, formats the moment based on the string given as its argument.
Take a look at the Moment.js docs and have a little decipher of the code; it will help you understand Moment.js as a library much better. Hope this helps.
I'm building a simple birthday reminder app where I get the names and birthdays in JSON and I need to display the names sorted based on whose birthday is coming next.
My logical thought would be to get the current day and month subtract that from the birthday and then do some kind of sort. But then how would do I handle -ve results or situations like when we are in Dec etc. I was guessing there might have been an simpler solution, but I'm quite clueless.
Here is a plunkr with the base working code: http://plnkr.co/edit/AkP6FRRG917TDdTtfWM7?p=preview
As others suggested, convert the string to a unix timestamp or date.
Here's an updated Plunker.
The controller adds a fromNow variable to the data:
$scope.friends.forEach(function(data){
var day = data.birthday.split("/")
var currentYear = new Date().getFullYear();
var birthdayDate = new Date(currentYear, day[0] - 1, day[1])
var now = new Date().valueOf();
if (birthdayDate.valueOf() < now){
birthdayDate.setFullYear(currentYear+1)
}
data.fromNow = birthdayDate.valueOf() - now;
})
Get the individual date/month parts (so we get a list like ["02","14","1985"])
Create a date object based on the current year, the month day[0] and the day day[1]. (Note we subtract 1 from the months because months are 0-based in in Javascript).
Get a numeric value for the current date/time
If the birthday is in the past add one year
Assign the number of milliseconds between now and the birthday to fromNow
You'd need to modify it so that if someone's birthday is today it doesn't add a year, thus placing it last in the list.
Also note I've added quotes to the orderBy parameter:
<tr ng-repeat="friend in friends| orderBy:'fromNow' ">
I would go about this by converting the dates to unix timestamps (int values) and doing a simple sort on them.
Convert date to timestamp using javascript Date.parse()
Convert the current date and birthdate to UNIX time and compare them based on the differences between these two values
birthdates = [new Date(1988,01,27), new Date(2013,01,01)];
birthdates.sort(function(firstDate,secondDate){
//calculate the difference between first date and current date
firstDifference = new Date() - firstDate;
//calculate difference between second date and current date.
secondDifference = new Date() - secondDate;
//return the smallest value.
return firstDifference - secondDifference;
});
//display the sorted array.
alert(birthdates);
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Compare 2 dates with JavaScript
Hi,
I'm working on form validation for my application and i want to know where i would be to start looking at to find date comparison eg a start date and an end date. The dates inputted in to my application are in the form: DD/MM/YYYY.
Thanks in Advance,
Dean
If you are using the Javascript Date object, you can simply do:
var startDate = new Date();
var endDate = getEndDate();
if (endDate < startDate)
alert("Houston, we've got a problem!");
EDIT: Changed naming a bit just to stick to camelCase convention, even though I despise it.
this function lets you convert dates to timestamps with wich you could work:
http://caioariede.com/arquivos/strtotime.js
First, you'll want to parse the text into Date objects, then use the language's built-in date comparison. For example:
var dateStr = document.getElementById('foo').value;
var date = Date.parse(dateStr);
var dateStr2 = document.getElementById('foo2').value;
var date2 = Date.parse(dateStr2);
if (date < date2) {
// ...
}