Javascript Adding Time for a Future Date - javascript

I looked at some other questions, and don't see my specific problem, so please excuse me if it has been asked or answered.
What I am trying to do is figure out a simple "payment" calculator, and provide some additional information, such as the first payment date, and the last.
In some cases, the day of the last payment works, and sometimes it doesn't.
Here's my code:
var myDate = new Date();
var odo = document.contract.firstPaymentDate.value;
var n = odo.split("/");
var month = n[0];
var day = n[1];
var year = n[2];
var oldDateObj = new Date(year, month, day);
var newDateObj = new Date(oldDateObj.getTime() + ((document.contract.totalNumberRegularPayments.value - 1)*1209600*1000));
var dd = newDateObj.getDate();
var mm = newDateObj.getMonth();
var y = newDateObj.getFullYear();
var someFormattedDate = mm + '/'+ dd + '/'+ y;
document.contract.lastPaymentDate.value = someFormattedDate;
So I take the first payment date, and add 1209600 seconds times the number of payments (minus 1 since they have "already" paid the first).
This is based on starting at a specific day that can be chosen by the user.
So my example is 156 BiWeekly payments (so 155 for the calculations), which works out to 6 years. If I choose the date of the 1st, I get 10/01/2013 as the start, but 9/11/2019 as the end (First on a Tuesday, last on a Wednesday).
For the 15th (9/15/2013 - a Sunday - to 8/24/2019 - a Saturday)
For the 20th (9/20/2013 - a Friday - to 8/29/2013 - a Thursday)
So since sometimes it's a day later, and sometimes a day ahead, I can't just +1 to var dd = newDateObj.getDate();
I'm really baffled as to what's going on, and I'm hoping someone out there either has some experience with this, or someone that knows what the heck I might be doing wrong.
Thanks in advance for any help you can offer.

If you want to add a number of weeks, just add 7 times as many days, e.g.
var now = new Date();
// Add two weeks
now.setDate(now.getDate() + 14);
So if you have 24 fortnightly payments:
var now = new Date();
// Add 24 fortnights (48 weeks)
now.setDate(now.getDate() + 24 * 14);
or
now.setDate(now.getDate() + 24 * 2 * 7);
whatever you think is clearest.
If you want to have a start and end date:
var start = new Date();
var end = new Date(+start);
end.setDate(end.getDate() + 24 * 14);
alert('Start on: ' + start + '.\nEnd in 24 fortnights: ' + end);
Edit
Here's a working example:
<script>
function calcLastPayment(start, numPayments) {
if (typeof start == 'string') {
start = stringToDate(start);
}
var end = new Date(+start);
end.setDate(end.getDate() + --numPayments * 14)
return end;
}
// Expect date in US format m/d/y
function stringToDate(s) {
s = s.split(/\D/)
return new Date(s[2], --s[0], s[1])
}
</script>
<form>
<table>
<tr><td>Enter first payment date (m/d/y):
<td><input name="start">
<tr><td>Enter number of payments:
<td><input name="numPayments">
<tr><td colspan="2"><input type="button" value="Calc end date" onclick="
this.form.end.value = calcLastPayment(this.form.start.value, this.form.numPayments.value)
">
<tr><td>Last payment date:
<td><input readonly name="end">
<tr><td colspan="2"><input type="reset">
</table>
</form>
Given a first payment date of Thursday, 5 September and 3 repayments it returns Thursday 3 October, which seems correct to me (5 and 19 September and 3 October). It should work for any number of payments.

There is a simple way to do this in a line or two of code.
I use 864e5 for the number of milliseconds in a day. Because 1000 milliseconds/second * 60 seconds/minute * 60 minutes/hour * 24 hours/day = 86400000 milliseconds/day or 864e5.
var now = new Date,
day = 864e5,
weekFromNow = new Date(+now + day * 7); //+now casts the date to an integer
+now casts the date to an integer, the number of milliseconds. now.valueOf() works too.
day * 7 or 864e5 * 7 is the number of milliseconds in a week.
new Date(...) casts the number of milliseconds to a date again.
Sometimes you don't have to worry about casting the value back to a date.

Related

Get the current week using JavaScript without additional libraries ? [SO examples are broken]

I built a calendar control and was adding the week numbers as a final touch, and encountered a problem with every script example I could find on SO and outside of SO (most of which one has copied from the other).
The issue is that when dates fall in partial months, the week calculation seems to mess up and either continue counting when it is the same week in a new month, or it thinks the last full week in a previous month is the same week number as the first full new week in the following month.
Following is a visual demonstration of one of the libraries (they all have their inaccuracies as they generally base their week calculation off a fixed number and build from there) :
You can view the codepen here as the project is rather complex, I have the Date.prototype.getWeek function at the start to play with this easier. Feel free to swap in any code from the samples found here on SO as they all end up funking out on some months.
Some of the calculations used :
Show week number with Javascript?
Date get week number for custom week start day
w3resource.com ISO86901
epoch calendar - getting ISO week
Get week of year in JavaScript like in PHP
When running the most current example (2017) from "Get week of year in JavaScript like in PHP", the week returned right now is 42. When you look on my calendar, the week in October right now is showing as 42 which is correct according to here https://www.epochconverter.com/weeks/2018.
Given the example, there are full weeks sharing the same week number - so I don't see how 42 can even be accurate.
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */
dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
Here is some code (also tried this) that is Sunday specific (see near the bottom). I am also pasting the relevant snip here :
/* For a given date, get the ISO week number
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
The algorithm is to use the week number of the following Saturday. So get the following Saturday, then use it's year for the 1st of Jan. If it's not a Sunday, go to the previous Sunday. Then get the number of weeks from there. It might sound a bit convoluted, but it's only a few lines of code. Most of the following is helpers for playing.
Hopefully the comments are sufficient, getWeekNumber returns an array of [year, weekNumber]. Tested against the Mac OS X Calendar, which seems to use the same week numbering. Please test thoroughly, particularly around daylight saving change over.
/* Get week number in year based on:
* - week starts on Sunday
* - week number and year is that of the next Saturday,
* or current date if it's Saturday
* 1st week of 2011 starts on Sunday 26 December, 2010
* 1st week of 2017 starts on Sunday 1 January, 2017
*
* Calculations use UTC to avoid daylight saving issues.
*
* #param {Date} date - date to get week number of
* #returns {number[]} year and week number
*/
function getWeekNumber(date) {
// Copy date as UTC to avoid DST
var d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Shift to the following Saturday to get the year
d.setUTCDate(d.getUTCDate() + 6 - d.getUTCDay());
// Get the first day of the year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
yearStart.setUTCDate(yearStart.getUTCDate() - yearStart.getUTCDay());
// Get difference between yearStart and d in milliseconds
// Reduce to whole weeks
return [d.getUTCFullYear(), (Math.ceil((d - yearStart) / 6.048e8))];
}
// Helper to format dates
function fDate(d) {
var opts = {weekday:'short',month:'short',day:'numeric',year:'numeric'};
return d.toLocaleString(undefined, opts);
}
// Parse yyyy-mm-dd as local
function pDate(s){
var b = (s+'').split(/\D/);
var d = new Date(b[0],b[1]-1,b[2]);
return d.getMonth() == b[1]-1? d : new Date(NaN);
}
// Handle button click
function doButtonClick(){
var d = pDate(document.getElementById('inp0').value);
var span = document.getElementById('weekNumber');
if (isNaN(d)) {
span.textContent = 'Invalid date';
} else {
let [y,w] = getWeekNumber(d);
span.textContent = `${fDate(d)} is in week ${w} of ${y}`;
}
}
Date:<input id="inp0" placeholder="yyyy-mm-dd">
<button type="button" onclick="doButtonClick()">Get week number</button><br>
<span id="weekNumber"></span>

Increment JavasScript date object for next month when days are increased?

Is there a simple solution to auto increment the month of the date object when days are added via getDate?
I need to add 2 days to a user supplied date, for example if the user's entered value is 2014-11-16 it returns 2014-11-18.
I have this working in the below example, but the problem is if a user supplies a date at the end of the month, for example 2014-11-30 it will return 2014-11-32 (November only has 30 days) instead of rolling into the next month, it should be 2014-12-02.
It also does not increment to a new year as well.
var actualDate = new Date(arrive);
var year = actualDate.getFullYear();
var monthy = actualDate.getMonth()+1;
var days = actualDate.getDate()+2;
var out = year + '-' + (monthy < 10 ? '0' : '') + monthy + '-' + days;
http://jsfiddle.net/bubykx1t/
Just use the setDate() method.
var actualDate = new Date(arrive);
actualDate.setDate(actualDate.getDate() + 2);
Check out this link
You can create new Date objects based on the number of milliseconds since January 1, 1970, 00:00:00 UTC. Since the number of milliseconds in a minute, hour, day, week are set we can add a fixed amount to the current time in order to get a time in the future. We can forget about what day of the month, or year it is as it's inherent in the number of milliseconds that have passed since 1970.
This will keep adjust to days months and years correctly.
var numberOfDaysToIncrement = 7;
var offset = numberOfDaysToIncrement * 24 * 60 * 60 * 1000;
var date = new Date();
var dateIncremented = new Date(date.getTime() + offset);

JavaScript calculate years and days from start date

I have date when someone is born, and I need to calculate with JavaScript or jQuery or so, how many years, days since birth date, until now.
So result can be like 20 years, 89 days.
I need to have same results as Wikipedia does with their function of "age in years", as it takes leap years in account and what not. So far I got code that works, but in some cases makes mistake of 1 day. My function is:
function DateDiff(date1, date2){
var res=((date1.getTime() - date2.getTime())/1000/60/60/24)-offset_d;
var full_days=Math.floor(res/365.25);
var f1=Math.round((res%365.25))
return full_days + " years, " +f1 + " days" ; }
Thanks for your help, I am doing this for days.
I wrote the following a while back, you should be able to tweak it to do the job:
// Given a date object, calcualte the number of
// days in the month
function daysInMonth(x) {
var d = new Date(x);
d.setDate(1);
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d.getDate();
}
/* For person born on birthDate, return their
** age on datumDate.
**
** Don't modify original date objects
**
** tDate is used as adding and subtracting
** years, months and days from dates on 29 February
** can affect the outcome,
**
** e.g.
**
** 2000-02-29 + 1 year => 2001-03-01
** 2001-03-01 - 1 year => 2000-03-01 so not symetric
**
** Note: in some systems, a person born on 29-Feb
** will have an official birthday on 28-Feb, other
** systems will have official birthday on 01-Mar.
*/
function getAge(birthDate, datumDate) {
// Make sure birthDate is before datumDate
if (birthDate - datumDate > 0) return null;
var dob = new Date(+birthDate),
now = new Date(+datumDate),
tDate = new Date(+dob),
dobY = dob.getFullYear(),
nowY = now.getFullYear(),
years, months, days;
// Initial estimate of years
years = nowY - dobY;
dobY = (dobY + years);
tDate.setYear(dobY);
// Correct if too many
if (now < tDate) {
--years;
--dobY;
}
dob.setYear(dobY);
// Repair tDate
tDate = new Date(+dob);
// Initial month estimate
months = now.getMonth() - tDate.getMonth();
// Adjust if needed
if (months < 0) {
months = 12 + months;
} else if (months == 0 && tDate.getDate() > now.getDate()) {
months = 11;
}
tDate.setMonth(tDate.getMonth() + months);
if (now < tDate) {
--months;
dob.setMonth(tDate.getMonth() - 1);
}
// Repair tDate
tDate = new Date(+dob);
// Initial day estimate
days = now.getDate() - tDate.getDate();
// Adjust if needed
if (days < 0) {
days = days + daysInMonth(tDate);
}
dob.setDate(dob.getDate() + days);
if (now < dob) {
--days;
}
return years + 'y ' + months + 'm ' + days + 'd';
}
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
window.onload = function() {
var form = document.forms['ageCalc'];
form.onsubmit = function() {
var dob = parseDMY(form.dob.value);
form.age.value = isNaN(dob)? 'Invalid date' : getAge(dob, new Date());
return false;
}
}
<form id="ageCalc">
<table>
<tr>
<td>Date of Birth (d/m/y)
<td><input name="dob">
<tr>
<td>Age today (y, m, d)
<td><input readonly name="age">
<tr>
<td><input type="reset">
<td><input type="submit" value="Calculate Age">
</table>
</form>
Here's a straight years and days version:
function diffInYearsAndDays(startDate, endDate) {
// Copy and normalise dates
var d0 = new Date(startDate);
d0.setHours(12,0,0,0);
var d1 = new Date(endDate);
d1.setHours(12,0,0,0);
// Make d0 earlier date
// Can remember a sign here to make -ve if swapped
if (d0 > d1) {
var t = d0;
d0 = d1;
d1 = t;
}
// Initial estimate of years
var dY = d1.getFullYear() - d0.getFullYear();
// Modify start date
d0.setYear(d0.getFullYear() + dY);
// Adjust if required
if (d0 > d1) {
d0.setYear(d0.getFullYear() - 1);
--dY;
}
// Get remaining difference in days
var dD = (d1 - d0) / 8.64e7;
// If sign required, deal with it here
return [dY, dD];
}
alert(diffInYearsAndDays(new Date(1957, 11, 4), new Date(2012, 11, 2))); // [54, 364]
You could roll your own... but I would highly recommend something like Moment.js. It is a solid library that has been proven in the field for calculating Math like this. It is only 4k, so I think you will be fine on size also.
At end solution was not related to any libraty but logic. I set start age hours and minutes to same as current day hour and minute. Then I keep adding 12 months until year is over current. That was for counting full years. I then set last "birthday" that is not over current date to be info to take and use standard date difference in days against that date and current date.
It worked as charm.
Thanks everyone on great help. It helped me focus on topic.

Show week number with Javascript?

I have the following code that is used to show the name of the current day, followed by a set phrase.
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array(
"It's Sunday, the weekend is nearly over",
"Yay! Another Monday",
"Hello Tuesday, at least you're not Monday",
"It's Wednesday. Halfway through the week already",
"It's Thursday.",
"It's Friday - Hurray for the weekend",
"Saturday Night Fever");
var now = new Date();
document.write(dayNames[now.getDay()] + ".");
// -->
</script>
What I would like to do is have the current week number in brackets after the phrase. I have found the following code:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Which was taken from http://javascript.about.com/library/blweekyear.htm but I have no idea how to add it to existing javascript code.
Simply add it to your current code, then call (new Date()).getWeek()
<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var weekNumber = (new Date()).getWeek();
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>
In case you already use jQuery-UI (specifically datepicker):
Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }
Usage:
var myDate = new Date();
myDate.getWeek();
More here: UI/Datepicker/iso8601Week
I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jQuery-UI this might just be a simple fit for someone - as it was for me.
If you don't use jQuery-UI and have no intention of adding the dependency. You could just copy their iso8601Week() implementation since it is written in pure JavaScript without complex dependencies:
// Determine the week of the year (local timezone) based on the ISO 8601 definition.
Date.prototype.iso8601Week = function () {
// Create a copy of the current date, we don't want to mutate the original
const date = new Date(this.getTime());
// Find Thursday of this week starting on Monday
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
const thursday = date.getTime();
// Find January 1st
date.setMonth(0); // January
date.setDate(1); // 1st
const jan1st = date.getTime();
// Round the amount of days to compensate for daylight saving time
const days = Math.round((thursday - jan1st) / 86400000); // 1 day = 86400000 ms
return Math.floor(days / 7) + 1;
};
console.log(new Date().iso8601Week());
console.log(new Date("2020-01-01T00:00").iso8601Week());
console.log(new Date("2021-01-01T00:00").iso8601Week());
console.log(new Date("2022-01-01T00:00").iso8601Week());
console.log(new Date("2023-12-31T00:00").iso8601Week());
console.log(new Date("2024-12-31T00:00").iso8601Week());
Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)
Date.prototype.getWeek = function(){
// We have to compare against the first monday of the year not the 01/01
// 60*60*24*1000 = 86400000
// 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01
var day_miliseconds = 86400000,
onejan = new Date(this.getFullYear(),0,1,0,0,0),
onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
days_for_next_monday = (8-onejan_day),
onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
// If one jan is not a monday, get the first monday of the year
first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
this_time = this_date.getTime(),
days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));
var first_monday_year = new Date(first_monday_year_time);
// We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
// then 7/7 = 1, and as we are 7 days from first monday,
// we should be in week number 2 instead of week number 1 (7/7=1)
// We consider week number as 52 when "days_from_first_monday" is lower than 0,
// that means the actual week started before the first monday so that means we are on the firsts
// days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
// so friday 01/01 is part of week number 52 from past year)
// "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong
return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}
You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek (Tests included)
If you want something that works and is future-proof, use a library like MomentJS.
moment(date).week();
moment(date).isoWeek()
http://momentjs.com/docs/#/get-set/week/
It looks like this function I found at weeknumber.net is pretty accurate and easy to use.
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you're lucky like me and need to find the week number of the month a little adjust will do it:
// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you already use Angular, then you could profit $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
By adding the snippet you extend the Date object.
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.
All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:
getDaysDiff = function (dateObject0, dateObject1) {
if (dateObject0 >= dateObject1) return 0;
var d = new Date(dateObject0.getTime());
var nd = 0;
while (d <= dateObject1) {
d.setDate(d.getDate() + 1);
nd++;
}
return nd-1;
};
I was coding in the dark (a challenge) and couldn't lookup, bring in any dependencies or test my code.
I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code instead.
var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()
console.log(week)
Just a proof of concept of how you can get the week in any other way
But still i recommend any other solution that isn't required by the DOM.
With that code you can simply;
document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");
(You will need to paste the getWeek function above your current script)
You could find this fiddle useful. Just finished.
https://jsfiddle.net/dnviti/ogpt920w/
Code below also:
/**
* Get the ISO week date week number
*/
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() != 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}
/**
* Get the ISO week date year number
*/
Date.prototype.getWeekYear = function ()
{
// Create a new date object for the thursday of this week
var target = new Date(this.valueOf());
target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);
return target.getFullYear();
}
/**
* Convert ISO week number and year into date (first day of week)
*/
var getDateFromISOWeek = function(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
var printDate = function(){
/*var dateString = document.getElementById("date").value;
var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field
var dateInput = document.getElementById("date").value;
if (dateInput == ""){
var date = new Date(); // get today date object
}
else{
var date = new Date(dateInput); // get date from field
}
var day = ("0" + date.getDate()).slice(-2); // get today day
var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month
var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date
var year = date.getFullYear();
var week = ("0" + (date.getWeek())).slice(-2);
var locale= "it-it";
document.getElementById("date").value = fullDate; // set input field
document.getElementById("year").value = year;
document.getElementById("week").value = week; // this prototype has been written above
var fromISODate = getDateFromISOWeek(week, year);
var fromISODay = ("0" + fromISODate.getDate()).slice(-2);
var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);
var fromISOYear = date.getFullYear();
// Use long to return month like "December" or short for "Dec"
//var monthComplete = fullDate.toLocaleString(locale, { month: "long" });
var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;
var element = document.getElementById("fullDate");
element.value = formattedDate;
}
printDate();
document.getElementById("convertToDate").addEventListener("click", printDate);
*{
font-family: consolas
}
<label for="date">Date</label>
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />
<br /><br />
<label for="year">Year</label>
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />
-
<label for="week">Week</label>
<input type="text" id="week" style="width:25px;text-align:center" value="" />
<br /><br />
<label for="fullDate">Full Date</label>
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />
<br /><br />
<button id="convertToDate">
Convert Date
</button>
It's pure JS.
There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)
Luxon is an other alternative. Luxon date objects have a weekNumber property:
let week = luxon.DateTime.fromString("2022-04-01", "yyyy-MM-dd").weekNumber;
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
I've tried using code from all of the answers above, and all return week #52 for the first of January. So I decided to write my own, which calculates the week number correctly.
Week numeration starts from 0
Maybe it's a bad taste to use a loop, or the result can be cached somewhere to prevent repeating the same calculations if the function is called often enough. Well, I have made this for myself, and it does what I need it to do.
Date.prototype.getWeek = function() {
// debugger
let msWeek = 604800000; // Week in milliseconds
let msDay = 86400000; // Day in milliseconds
let year = this.getFullYear(); // Get the year
//let month = this.getMonth(); // Month
let oneDate = new Date(year, 0, 1); // Create a new date based on THIS year
let temp = oneDate.getDay(); // Ordinal of the first day
let getFirstDay = (temp === 0) ? 6 : temp - 1; // Ordinal of the first day of the current month (0-MO, 6-SU)
let countWeek = 0;
// Test to confirm week
oneDate = new Date(oneDate.getTime() + msDay*(7 - getFirstDay));
if(oneDate.getTime() > this.getTime()){
return countWeek;
}
// Increment loop
while(true){
oneDate = new Date(oneDate.getTime() + msWeek); // Add a week and check
if(oneDate.getTime() > this.getTime()) break;
countWeek++;
}
return countWeek + 1;
}
let s1 = new Date('2022-01-01'); console.log(s1.getWeek());
let s2 = new Date('2023-01-01'); console.log(s2.getWeek());
let s22 = new Date('2023-01-02'); console.log(s22.getWeek());
let s3 = new Date('2024-01-01'); console.log(s3.getWeek());
let s4 = new Date('2025-01-01'); console.log(s4.getWeek());
let s5 = new Date('2022-02-28'); console.log(s5.getWeek());
let s6 = new Date('2022-12-31'); console.log(s6.getWeek());
let s7 = new Date('2024-12-31'); console.log(s7.getWeek());
Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.
Here is a revised and working version:
Date.prototype.getWeek = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
return 1 + Math.ceil(dayDiff / 7);
}
else { // jan 4th is on the next week (so next week is week 1)
return Math.ceil(dayDiff / 7);
}
};
Martin Schillinger's version seems to be the strictly correct one.
Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:
ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );
It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

Using answers from prompt for a calculation

Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp

Categories

Resources