Get date from days into year (Javascript) - javascript

I am getting the days into the year using this code:
function daysIntoYear(){
let date = new Date();
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
Which tells me how many days have passed in the year. From a number like this (it will change), how can I get a date object which tells me exactly what month and day and year the day is in.
For example:
an input of 1 should output (the current year, 2021) as the year, January as the month, and 1 as the day into the month of January.
An input of 102 (the current day) should output something like April 12th 2021.
Is this possible?
Assume the year is always the current year. Thanks.
Thanks to #NiettheDarkAbsol in the comments, I was able to solve this using this code:
function daysIntoYear(){
let date = new Date();
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
let finalDate = new Date(new Date().getFullYear(), 0, daysIntoYear());
Thanks again!

I solved this using this code:
function daysIntoYear(){
let date = new Date();
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
let finalDate = new Date(new Date().getFullYear(), 0, daysIntoYear())

Related

Day of Year does not update in JavaScript?

I have JavaScript Code that calculates the day of the year (for example, January 1 would be 1 and October 30 would be 304):
var now = new Date();
//leap year rules:
// The year must be evenly divisible by 4;
// If the year can also be evenly divided by 100, it is not a leap year
// Unless the year is also evenly divisible by 400. Then it is a leap year.
if(now.getUTCFullYear() % 4 == 0){
//if the year is a leap year:
if(now.getUTCFullYear() % 100 != 0){
var day = Math.ceil((now - new Date(now.getFullYear(),0,1)) / 86400000);
document.getElementById('dayOfYear').innerHTML = day;
}
else if(now.getUTCFullYear() % 100 == 0 && now.getUTCFullYear() % 400 == 0){
var day = Math.ceil((now - new Date(now.getFullYear(),0,1)) / 86400000);
document.getElementById('dayOfYear').innerHTML = day;
}
else{
var day = Math.ceil((now - new Date(now.getFullYear(),0, 0)) / 86400000);
document.getElementById('dayOfYear').innerHTML = day;
}
}
else{
//if the year is NOT a leap year
var day = Math.ceil((now - new Date(now.getFullYear(),0, 0)) / 86400000);
document.getElementById('dayOfYear').innerHTML = day;
}
The code gets refreshed every second, since it is a clock app. However, when the clock hits 00:00:00 on the next day the Day of the Year does not update until hours later. What might be causing this?
Thanks!
You are creating a Date using local values, but counting UTC days so it ticks over at UTC midnight, not local midnight. Also, the algorithm is way too complex. Just use UTC for everything, e.g.
function getDayOfYear(d = new Date()) {
// Start of year
let yearStart = Date.UTC(d.getFullYear(), 0, 1);
// Get difference to now / ms in one day
return Math.floor(((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) - yearStart)) / 8.64e7) + 1;
}
[new Date(2020,0,1), // 1 Jan 2020
new Date(), // today
new Date(2020,11,31) // 31 Dec 2020
].forEach(d => console.log(d.toDateString() + ' is day ' + getDayOfYear(d)));
PS (Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) could also be (+d + d.getTimezoneOffset() * 6e4), which is a little shorter but maybe less readable.
To have it tick over at UTC midnight:
function getUTCDayOfYear(d = new Date()) {
// Start of year
let yearStart = Date.UTC(d.getUTCFullYear(), 0, 1);
// Get difference to now / ms in one day
return Math.floor(((Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - yearStart)) / 8.64e7) + 1;
}
[new Date(Date.UTC(2020,0,1)), // 1 Jan 2020 UTC
new Date(Date.UTC(2020,11,31)) // 31 Dec 2020 UTC
].forEach(d => console.log(d.toString() + ' is on UTC day ' + getUTCDayOfYear(d)));

JS/PHP, time of date

i would like to ask, if someone know to to make in JS or PHP time of date.
Or how long we're together, like 70 days or 2 month and some days, and all day add 1 more day. I have something whats work, but on begging of that time is - .
I spent a lot time with making something what should work. But nothing.
There is that code with that -
<script charset="UTF-8">
function daysTill() {
var day= 8
var month= 12
var year= 2016
var event= "relationship with my ♥"
var end = "days of"
var daystocount=new Date(year, month -1, day)
today=new Date()
if (today.getMonth()==month && today.getDate()>day)
daystocount.setFullYear(daystocount.getFullYear())
var oneday=1000*60*60*24
var write = (Math.ceil((daystocount.getTime()-today.getTime())/(oneday)))
document.write('<strong>'+write +'</strong> '+end+' '+event)
}
daysTill();
</script>
if someone know, please help me. Thanks ♥
The getTime() method returns the time in milliseconds so to convert it to days you divide that by 86400000 (1000 for seconds * 60 for minutes * 60 for hours * 24 for days):
var relationship = new Date("2016/12/08");
var today = new Date();
var days = Math.ceil((today.getTime() - relationship.getTime()) / 86400000);
document.write(days + " days have pass since the start of the relationship.");
Try to use "JavaScript date maths"
// new Date(year, month (0-11!), day, hours, minutes, seconds, milliseconds);
var dateFuture = new Date(2017, 3, 1, 9, 0, 0, 0);
var dateLongAgo = new Date(2001, 8, 11, 8, 46, 0, 0);
var dateNow = new Date();
//86400000 millis per day
//floor --> all unter a full day shall be 'no day'
var daysSince = Math.floor((dateNow-dateLongAgo)/86400000);
var daysUntil = Math.floor((dateFuture-dateNow)/86400000);
console.log("long ago\t", dateLongAgo);
console.log("now is\t\t",dateNow);
console.log("then\t\t",dateFuture);
console.log("days since\t",daysSince);
console.log("days until\t", daysUntil);
If you don't mind using external libraries, Carbon is a nice tool extending DateTime
http://carbon.nesbot.com/docs/
It returns many kinds very nicely formatted dates -- months, days, hours etc included.

How to calculate and check for a bi-weekly date

I really need your help,
Let's say my demarcation start date is: December 19, 2016 as defined by the variable x
How can I write a JavaScript function, such that it will check the present date against x and the present date against what the recurrence date will be (14) days from x as defined by the variable y.
var y = recurrence is every 14 days, thereafter from the date (x) with no end date specified (unlimited)
Ex.
function() {
if (present date == x) { alert(true) }
if (present date == y) { alert(true) }
}
You could get the number of days difference between your start date and the current date then check if that number is a multiple of 14.
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return Math.floor((treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay);
}
var demarcationdate = new Date("2016-12-19"),
today = new Date(),
days = daysBetween(demarcationdate,today),
daystill = 14 - days%14,
rec = days%14==0,
d = new Date();
d.setDate(today.getDate() + daystill);
var nextDate = (d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
console.log("Days diff = "+days+". Recurs today = "+rec+". Next in "+daystill+" days ("+nextDate.toString()+").");
jsFiddle
If Date.now() == 1482181410856, 14 days from now will be 1482181410856 + (14 * 24 * 60 * 60 * 1000) == 1483391010856.
let y = new Date(Date.now() + (14 * 24 * 60 * 60 * 1000));
console.log(y.toUTCString()); // "Mon, 02 Jan 2017 21:03:30 GMT"
Assuming you really want to compare precise dates, i.e. to the milliseconds, then:
var present_date = new Date();
if(present_date.getTime() === x.getTime()) alert("Today is the same date as x");
else {
var y = new Date(x.getTime());
y.setDate(y.getDate() + 14); // add 14 days
if(present_date.getTime() === y.getTime()) alert("Today is the same date as y");
}
But most of the time we want to compare dates as full days, not milliseconds, so you'd have to compare ranges instead (from midnight to 11:59PM)... In that case, I recommend using a library to make your life easier - like moment.js for instance...
Hope this helps!
This is probably a duplicate of Add +1 to current date.
If you have a start date, say 20 December, 2016, you can calculate 14 days after that by simply adding 14 days to the date. You can then check if today's date is either of those dates, e.g.
// Create a Date for 20 December, 2016 with time 00:00:00
var startDate = new Date(2016,11,20);
// Create a Date for the start + 14 days with time 00:00:00
var startPlus14 = new Date(startDate);
startPlus14.setDate(startPlus14.getDate() + 14);
// Get today and set the time to 00:00:00.000
var today = new Date();
today.setHours(0,0,0,0);
if (+today == +startDate) {
console.log('Today is the start date');
} else if (+today == +startPlus14) {
console.log('Today is 14 days after the start date');
} else {
console.log('Today is neither the start nor 14 days after the start');
}

Number of weeks between two dates using JavaScript

I'm trying to return the number of weeks between two dates using JavaScript.
So I have the following variables:
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if(day < 10) { day= '0' + day; }
if(month < 10) { month = '0' + month; }
var dateToday = day + '/' + month + '/' + year;
var dateEndPlacement = '22/06/2014';
I've also prefixed the days and months with 0 if they are less than 10. Not sure if this is the correct way to do this... so alternative ideas would be welcomed.
And then I pass these two dates to the following function:
function calculateWeeksBetween(date1, date2) {
// The number of milliseconds in one week
var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to weeks and return hole weeks
return Math.floor(difference_ms / ONE_WEEK);
}
However I get the error:
Uncaught TypeError: Object 04/04/2014 has no method 'getTime'
Any ideas what I am doing wrong?
For those that are asking/gonna ask, I'm calling the function like this:
calculateWeeksBetween(dateToday, dateEndPlacement);
I would recommend using moment.js for this kind of thing.
But if you want to do it in pure javascript here is how I would do it:
function weeksBetween(d1, d2) {
return Math.round((d2 - d1) / (7 * 24 * 60 * 60 * 1000));
}
Then call with
weeksBetween(new Date(), new Date(2014, 6, 22));
You are storing your dates as strings ('22/06/2014'). getTime is a method of Date. You need to create Date objects for the dates, and pass those into the function.
var dateToday = new Date(year, month - 1, day);
var dateEndPlacement = new Date(2014, 5, 22);
calculateWeeksBetween(dateToday, dateEndPlacement);
As #Mosho notes, you can also subtract the dates directly, without using getTime.
If you need actual weeks between to dates, and not the number of seven days between them:
const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;
function startOfWeek(dt) {
const weekday = dt.getDay();
return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}
function weeksBetween(d1, d2) {
return Math.ceil((startOfWeek(d2) - startOfWeek(d1)) / week);
}
You can use moment itself have all the functionality I mentioned the below code which could work perfectly
var a = moment(a, 'DD-MM-YYYY');
var b = moment(b, 'DD-MM-YYYY');
days=b.diff(a, 'week');
don't forget to use moment js CDN
subtract dates (which, unformatted, are the number of seconds elapsed since 1 January 1970 00:00:00) , divide by 604,800,000 (milliseconds per week).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You should convert dateToday and dateEndPlacement to Date type.
Please read Converting string to date in js

How to calculate date range for week and month in javascript?

Can someone guide me on date range in JavaScript?
I want to calculate one week and month date range from today's date; I.e, if today is "18th july 2010", the range for the week should be "11/07/2010 - 8/07/2010"
and for the month it should be "01/07/2010 - 18/07/2010".
Thanks for your guidance in advance.
Try this:
var now = new Date();
var nextWeek = new Date(new Date(now).setDate(now.getDate() + 7));
var nextMonth = new Date(new Date(now).setMonth(now.getMonth() + 1));
I would recommend you looking at the excellent datejs library which has many useful functions to manipulate dates.
Here is vanilla JS function that will take a date (or blank) as input and return an object with start and end date of that week (assuming Monday is first day of week :) )
function rangeWeek (dateStr) {
if (!dateStr) dateStr = new Date().getTime();
var dt = new Date(dateStr);
dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
dt = new Date(dt.getTime() - (dt.getDay() > 0 ? (dt.getDay() - 1) * 1000 * 60 * 60 * 24 : 6 * 1000 * 60 * 60 * 24));
return { start: dt, end: new Date(dt.getTime() + 1000 * 60 * 60 * 24 * 7 - 1) };
}
console.log(rangeWeek());
console.log(rangeWeek('2013/9/1'));
You can change accordingly for Sunday-Saturday.

Categories