Difference of two Dates shows 6 days too much - javascript

const oldDate= new Date('2019-07-19T19:20:00');
const newDate = new Date('2020-07-19T19:20:00'); // 1 year later
let timeDiff = new Date(newDate.getTime() - oldDate.getTime());
const years = timeDiff.getFullYear()-1970;
const months = timeDiff.getUTCMonth();
const days = timeDiff.getUTCDay(); // why 6 days ????
console.log(days);
I try to calc the difference between two dates and show it as years, months, days.
I really don't know if there is something wrong in the code or why are there 6 days as a difference? Should it be not 0?
const oldDate= new Date('2019-07-19T19:20:00');
const newDate = new Date('2020-07-19T19:20:00'); // 1 year later
let timeDiff = new Date(newDate.getTime() - oldDate.getTime());
const years = timeDiff.getFullYear()-1970;
const months = timeDiff.getUTCMonth();
const days = timeDiff.getUTCDay(); // why 6 days ????

As per MDN:
Date.prototype.getUTCDate()
Returns the day (date) of the month (1–31) in the specified date according to universal time.
Date.prototype.getUTCDay()
Returns the day of the week (0–6) in the specified date according to universal time.
So you likely wanted .getUTCDate(), not .getUTCDay().

Related

Convert number of days left into years, months, days [duplicate]

This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
How to get the difference of two dates in mm-dd-hh format in Javascript
(3 answers)
Closed 2 years ago.
I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :
const birthday = new Date ('11-20-2021').getTime();
const today = new Date ().getTime();
const dys = (1000*60*60*24);
const months = (dys*30);
let differance = birthday-today ;
const formatted = Math.round(differance/dys);
console.log(formatted);`
thank you in advance
How do you feel about the modulo operator? :)
This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...
I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.
this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/
moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:
import moment from 'moment';
import 'moment-precise-range-plugin';
var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
If I got you right, I've done it this way.
Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.
const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;
const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);
function daysToDateTime(totalDays) {
var baseVal = '';
var formedValues = [
['Years', 365],
['Months', 30],
['Days', 1]
];
for (var i = 0; i < formedValues.length; i++) {
var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months
if (valueByGroup >= 1) {
baseVal += (valueByGroup + formedValues[i][0]) + ', ';
totalDays -= valueByGroup * formedValues[i][1];
}
}
return baseVal;
}

Display current week in react-native

I need to display the current week of the month in the following format in react-native:
(Week 2: 05.10 - 11.10) (example of week 2 of current month)
What would be some suggestions as how to achieve this? I know that there are packages such as momentjs to build this but would like some examples of how to achieve this
any help is appreciated!
You can adapt the code below. I say "adapt" because you haven't specified when your week starts (Sunday or Monday?) or how you want to count which week within the month it is (i.e. is week #1 the first full week? The code below assumes so).
Anyway, by clicking the "Run Code Snippet" button, you'll see what it does, including some intermediate steps, which are there to illustrate where the values are coming from, and therefore what you might want to "adapt" for your needs.
//get the first day of week and last day of week, borrowed from https://stackoverflow.com/a/64529257/1024832 above
const getWeek = (date = new Date()) => {
const dayIndex = date.getDay();
const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));
return [dateOfMonday, dateOfSunday];
}
//get week number w/in the month, adapted from https://stackoverflow.com/a/57120367/1024832
const getWeekNumber = () => {
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(todaysDate).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
return weekOfMonth;
}
//capture/log some steps along the way
const [Monday, Sunday] = getWeek();
console.log("First/Last of week as Date Objects: ", Monday, Sunday);
let Monday_formatted = moment(Monday).format("DD.MM");
let Sunday_formatted = moment(Sunday).format("DD.MM");
console.log(Monday_formatted, "-", Sunday_formatted);
console.log("Week #:", getWeekNumber());
//set the DIV content
document.getElementById("datehere").innerText = `(Week ${getWeekNumber()}): ${Monday_formatted} - ${Sunday_formatted}`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<div id="datehere"></div>
Here's an answer as a function which returns the current week's Monday and Sunday in an array:
getWeek = (date = new Date()) => {
const dayIndex = date.getDay();
const diffToLastMonday = (dayIndex !== 0) ? dayIndex - 1 : 6;
const dateOfMonday = new Date(date.setDate(date.getDate() - diffToLastMonday));
const dateOfSunday = new Date(date.setDate(dateOfMonday.getDate() + 6));
return [dateOfMonday, dateOfSunday];
}
const [Monday, Sunday] = getWeek();
console.log(Monday, Sunday);
The response is two valid date objects. You can also pass a date object for the function to get Monday and Sunday of that date's week (e.g. getWeek(new Date(0));
But when you want to parse those dates, you should gain better knowledge of Date Object.

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Get date of exactly 6 days ago from today in JS [duplicate]

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 3 years ago.
Thank you in advance
I would like your help with getting 'days ago' from a particular date. I don't want to use any library.
Although I have tried moment JS.
Use getDate() and subtract the number of days from it
var d = new Date();
d.setDate(d.getDate() - 6);
console.log(d);
First, make a new Date with your date:
const date = new Date('December 17, 1995 03:24:00');
Second, subtract 6 days like so:
date.setDate(date.getDate() - 6);
Third, use date.toString() :
console.log(date.toString());
You question title and description contradict with each other.
The following function that return number of days ago can help if this is what you need:
function getDaysAgo(date, now = new Date()) {
//first calculating start of the day
const start = now.setHours(0, 0, 0, 0);
//then calculating difference in miliseconds
const diff = start - date.getTime();
//finally rounding to a bigger whole days
const result = Math.ceil(diff/(1000*60*60*24));
//as a bonus returning today/yesterday/future when necessary
if (result < 0) {
return 'in future';
}
if (result === 0) {
return 'today';
}
return result === 1 ? 'yesterday' : result + ' days ago';
}
For example getDaysAgo(new Date(Date.parse('2019-9-28 23:59')), new Date(Date.parse('2019-9-30 10:59'))) returns 2 days ago.
It is a simple function that returns a new desire past date.
function getNthDate(nthDate){
let date = new Date();
return new Date(date.setDate(date.getDate() - nthDate))
}
Live example

getYear() in JavaScript returns 118 [duplicate]

This question already has answers here:
Why does Javascript getYear() return a three digit number?
(14 answers)
getMonth in javascript gives previous month
(6 answers)
Closed 4 years ago.
I need to calculate the date of the last Monday that before the latest weekend. Having used what I believe to be the most common Stack Overflow suggestions I have the following code:
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const newNewDate = new Date(newDate.getTime());
console.log(newNewDate);
const day = newNewDate.getDate();
const month = newNewDate.getMonth();
const year = newNewDate.getYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
It returns the year as 118 and the month as 5 which are ... not that Monday I need. newNewDate, on the other hand is the last Monday. I was wondering what causes it. I am aware that there are too many reassignments that are not needed. Please help.
Whatever you are doing is perfect only, the only mistake is you are using getMonth() and getYear() and misunderstanding them.
date.getMonth() gives you months ranging from 0-11. So 5 is actually June month.
date.getYear() this method returns the year minus 1900, so actual is 118+1900=2018, instead you can use date.getFullYear() which will return 2018
Also, you don't need so many steps.
the function can be simply stopped with newDate as given below
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const day = newDate.getDate();
const month = newDate.getMonth() + 1;
const year = newDate.getFullYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
This will give "the year is 2018 the month is 6"
Hope this helps.

Categories