if you look at my date validation when i come to test if it is in the past it works although the date constructor expects a zero date month so how do i subtract one from the substring value representing the month (one from the result, not the position)
//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;
if (!date.match(dateformat))
{
errors.push("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
}
var today = new Date();
var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits
var courseDay = date.substr(0,2)//e the first and second digits
var dateToCompare = new Date(courseYear, courseMonth, courseDay);
if (dateToCompare < today) {
errors.push("this date is in the past");
}
so how do i subtract one
With the subtraction operator "-" and the number literal "1". It also has the benefit of converting the string to a number before. For year and day, you might use the unary plus to do that conversion explicitly (though the Date constructor does it implicitly):
new Date(+courseYear, courseMonth-1, +courseDay);
Related
I'm trying to compute the age of an individual using D3.js.
I have the following code :
d3.timeYear.count(Birth_date, Current_date);
Birth_date being an individual's birth date (a Date object), and Current_date being, well, the date at which I'd like to compute the individual's age. To be able to answer "if you were born on May 5th, 1975, how old were you on May 3rd, 1976".
d3.timeYear.count() seems to floor the dates to the beginning of the year, so that in my example my code will return 1 on January 1st, 1976, even though the guy was 5 months away from his first birthday.
I could count the number of days instead of years, but I might get wrong results locally depending on the number of days in the year.
The following is based on the JavaScript Date object and should do the job:
function age(by,bm,bd){
const D=new Date(), y=D.getFullYear(),
md=D.getMonth()-bm, dd=D.getDate()-bd;
return y-by-(md>0||!md&&dd>=0?0:1);
}
console.log(age(1992,8,26))
Basically I return the difference between the full year of today and the birthday. But I also check, whether the current month is either greater than the birthday-month or (||) if the month-difference is zero (!md is true) and (&&) the day-difference dd is greater than zero. If that is the case I subtract 0 otherwise 1 from the year-difference.
And please be aware that my age() function expects the month to be entered in JavaScript notation. This means that 8 in the above example refers to the month of September.
The answer by Carsten Massman has inspired me to make this function, which solves my problem :
function age(birthdate, currentdate){
const bDay = birthdate.getDate(); // Get the birthdate's day.
const bMonth = birthdate.getMonth(); // Get the birthdate's month.
const currYear = currentdate.getFullYear(); // Get the current date's year.
const currBirthday = new Date(currYear + "/" + (bMonth + 1) + "/" + bDay); // Contruct the date of the birthday in the current year
const daysToBirthday = d3.timeDay.count( d3.timeYear.floor(currBirthday), currBirthday); // Count the # of days since Jan. 1st this year
// Offset the current date in the past by the number of days computed above.
const offsetCurrent = d3.timeDay.offset(currentdate, -daysToBirthday);
// Compute the number of years between the two dates (floored to the beginning of their respective year).
return d3.timeYear.count(birthdate, offsetCurrent);
}
This computes the age for any birth date, and at any point in time afterwards, using mostly d3-time and a little bit of vanilla javascript's Date methods.
I am trying to get how many saturdays and sundays exist between two dates.
I get the first date from a input date field
<input value="" type="date" name="exit_end_document" id="exit_end_document" class="form-control" required>
My Javascript is this:
var fromDate = $('#exit_end_document').val();
I am getting the value.. the problem is that i do not know how can i calculate between that date which i get from input date field and today.
I have seen many examples but none of them do this...
(input date field) 2019-03-01 to (This date comes directly from JS) 2019-03-05 result = 2
Thanks!
Let's analyze this mathematically.
The starting date can either be on a Saturday or not. Likewise, the ending date can be either on a Saturday or not. In the simplest case, both dates are on Saturday; then you can see clearly that the number of Saturdays is equal to 1 plus the number of weeks between the two dates.
From there, it's easy to see that if the starting date is on a Saturday, but the ending date is not, then the number of Saturdays is equal to 1 plus the number of weeks between the two dates rounded down since the ending date's week has not reached Saturday yet. Turns out, that same math works for the first example, too, since you'll have an integer number of weeks between the dates. So we can cover both examples by simply using 1 + floor(weeks_between_dates) .
What if the ending date is a Saturday, but the starting date is not? Turns out, the math still works the same! This is the same as "moving back" the starting date from its Saturday, and that will add a partial week until it reaches the previous Saturday. Those partial weeks get rounded out by the floor, and once it reaches the previous Saturday, you'll be adding 1 anyway, as it'll be a full week added to the difference! So we're still good with 1 + floor(weeks_between_dates).
So the only possible combination left are two dates which are both not Saturday. This is the most complicated possibility. Let's start simple and assume the dates are two consecutive Wednesdays. Then they are 1 week apart and have 1 Saturday between them. Simple. If they're two weeks apart, they have 2 Saturdays. But what if it's a Wednesday and the following Tuesday? There is less than a week, but still 1 Saturday between them. And if it's a Wednesday and the following Thursday? More than 1 week, but still 1 Saturday! So in this case, we'd want to round the number of weeks up and stop there, giving us ceil(weeks_between_dates). But if they're both in the same week -- for instance, a Monday and a Friday in the same week -- then the answer is just 0. So how do we know whether the days are part of the same week? Assuming they're sorted and the start date is always before the ending date, then they're in the same week if and only if there is fewer than 1 week between them AND the starting weekday is before the ending weekday.
So the straight conditional logic here is this (in pseudocode):
weeks_between = floor((days between start and end) / 7)
if start.weekday = Saturday or end.weekday = Saturday, then:
return 1 + weeks_between
else if weeks_between = 0 and start.weekday is before end.weekday, then:
return 0
else
return ceil((days between start and end) / 7)
In order to handle leap years and timezones and whatnot, i suggest testing all the between days and testing them to see if they are sat or sunday:
var date1 = new Date("2012-06-04T05:00:00.000Z");
var date2 = new Date("2012-08-17T05:00:00.000Z");
var weekendDays = 0;
for(var i = +date1, mx = +date2; i<mx; i+=(1000*60*60*24)){
if({0:1,6:1}[new Date(i).getDay()]) weekendDays++;
}
alert(weekendDays); // 20
I already found the solution and it was given from #zak:
var fromDate = $('#exit_end_document').val();
fromDate = new Date(fromDate);
toDate = new Date();
var weekendDays = 0;
dayMilliseconds = 1000 * 60 * 60 * 24;
date1 = fromDate;
date2 = toDate;
while (date1 <= date2) {
var day = date1.getDay();
if (day == 0 || day == 6) {
weekendDays++;
}
date1 = new Date(+date1 + dayMilliseconds);
}
alert(weekendDays);
I need to get the start date and end date in the below format using moment js
startDate = 20160427000000 and
endDate = 20160427235959
Here the start date appended with 000000 and end date appended with 235959
What is the right way to get this result in javascript
You want the format operator. Since it looks like your 0's and 2359's are hardcoded (I assume you're doing start and end of days), try:
startDate = moment().format('YMMDD000000');
endDate = moment().format('YMMDD235959');
EDIT: Or, as RobG pointed out, you can use:
startDate = moment().startOf('day').format("YMMDDHHmmss");
endDate = moment().endOf('day').format("YMMDDHHmmss");
(Which is much neater)
I'm totally confused, I don't know if you want to parse the format or output it. If you want to parse dates using moment.js in that format, then in time zone +05:30:
// Format YYYYMMDDHHmmss for 2016-04-26T00:00:00
var s = '20160426000000';
var x = moment(s, 'YYYYMMDDHHmmss');
// Show date in ISO 8601 extended format
console.log(x.format()); // 2016-04-26T00:00:00+05:30
To shift to the end of the day and output in YYYMMDDHHmmss format:
console.log(x.endOf('day').format('YYYYMMDDHHmmss')); // 20160426235959
In the format string:
YYYY is 4 digit year
MM is two digit month
DD is two digit day
HH is two digit hour in 24 hour format
mm is two digit minute
ss is two digit seconds
For Getting Format Like these in moment.js - (2020-12-15T13:00:00)
let a =2023-01-14T20:15:00-05:00
You can use moment(a).format("YYYY-MM-DDTHH:mm:ss")
Result: 2023-01-14T20:15:00
I am trying to pick up value from datetimepicker tetxbox and compare those values with current time.
JSFiddle
//startTime textbox text = 19/12/2014 03:58 PM
var startTime = Date.parse($('[id$=txtStartDate]').val().toString());
//endTime textbox text = 19/12/2014 04:58 PM
var endTime = Date.parse($('[id$=txtEndDate]').val().toString());
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
if (currentTime >= startTime && currentTime <= endTime) {
alert();
}
Date.parse() is used fro converting string to milliseconds since Jan 1 1970.
Date.now() returns current date milliseconds since Jan 1 1970.
But the above conversion methods are not working properly.
What should be logic to compare datetime by first sonverting string in format like 19/12/2014 03:58 PM to Date object and then do comparing.
The problem is Date() expects date format mm/dd/yyyy, so your date is invalid.
You can fix your date like this:
function toValidDate(datestring){
return datestring.replace(/(\d{2})(\/)(\d{2})/, "$3$2$1");
}
var startTime = Date.parse(toValidDate($('[id$=txtStartDate]').val().toString()));
var endTime = Date.parse(toValidDate($('[id$=txtEndDate]').val().toString()));
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
DEMO: http://jsfiddle.net/3mztdaja/3/
Since that format isn't documented as being supported by Date.parse, your best bet is to parse it yourself, which isn't difficult: Use String#split or a regular expression with capture groups to split it into the individual parts, use parseInt to convert the parts that are numeric strings into numbers (or, with controlled input like this, just use the unary + on them), and then use new Date(...) to use those numbers to create a Date instance.
One gotcha: The month value that new Date expects is zero-based, e.g. 0 = January. Also remember to add 12 to the hours value if the input uses AM/PM instead of the 24-hour clock.
Or, of course, use any of several date/time handling libraries, such as MomentJS.
You should use this method
var startTime = new Date(year, month, day, hours, minutes, seconds, milliseconds);
this a demo http://jsfiddle.net/hswp7x8k/
to extrat value from string you can use this method
dd = '19/12/2014 03:58';
dd.match(/(\d+)\/(\d+)\/(\d+)\s*(\d+):(\d+)/);
this a demo http://jsfiddle.net/w3wow1ay/2/
I have this date parsed from an api as a string:
DD-MM-YYYY but sometimes the date is DD-M-YYYY or even D-M-YYYY.
For example:
4-1-2013
or
10-10-2013
or 7-4-2013
The year is always 4 digits but days or months sometimes get one digit. How can I manually (with JS) add 0 in front of a every single digit ?
I am using moment.js for some calculations thus I am remove the '-' using
date.replace("-", "")
to get a whole number (eg. 4-1-2013 = 412013) so I can use it with moment.js but if its a single digit, it all gets messed up.
You can normalise your strings first like this:
date = date.replace(/\b(\d{1})\b/g, '0$1');
which will take any "word" that is just a single digit and prepend a zero.
Note that to globally replace every - you must use the regexp version of .replace - the string version you've used only replaces the first occurrence, therefore:
date = date.replace(/\b(\d{1})\b/g, '0$1').replace(/-/g, '');
will do everything you require.
Moment.js supports formats with dashes, so you don't even need to do any string handling.
moment('4-1-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 04012013
moment('10-10-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 10102013
If the date variable is in a String format(for example from input[type=date]) then you need to split the data component into single items.
date = date.split('-');
then check both the day's and the month's length
day = date[0].length==1 ? "0"+date[0] : date[0];
month = date[1].length==1 ? "0"+date[1] : date[1];
then get them back together into a format that you desire
date = ""+day+month+date[2];
Working example: http://jsfiddle.net/dzXPE/
var day = new Date();
day = day.getDay();
if(day.toString().length <= 1) {
day = '0' + day;
}
You can use the same for month. I'm not entirely sure you need to convert to string but it wouldn't hurt.