Javascript time zone calculation issues - javascript

I am trying to make a countdown timer for ticket response expiry. My code will successfully calculate the time left when dealing with hours bar the extra hour (+0100) GMT.
I have tried dealing with this in all manner of ways suggested on here to no avail. Any suggestions? Should I give in & learn Luxon?
The converttoUTC function seen is not called as it has not worked & only messed up the calculation further.
The dates that's been pulled from the table is in the following format 2022-04-15 17:47:19
The Time Limits being pulled from the table are in the following format, "15 mins" "6 hours".
<!--===========================================================================================-->
<script>
function func(creationDatePlusLimit) {
// var dateValue= document.getElementById("date").value;
var date = Math.abs((new Date().getTime() / 1000).toFixed(0));
var date2 = Math.abs((new Date(createdOnDate).getTime() / 1000).toFixed(0));
var diff = date2 - date;
var days = Math.floor(diff / 86400);
var hours = Math.floor(diff / 3600) % 24;
var mins = Math.floor(diff / 60) % 60;
var secs = diff % 60;
// document.getElementById("data").innerHTML = days + " days, " + hours + ":" + mins + ":" + secs;
if (days>=0) {
return days + " days, " + hours + ":" + mins + ":" + secs;
} else {
return "late";
}
}
const loopThroughTableRows = () => {
const tableRows = Array.from(document.getElementsByTagName('tr'));
tableRows.shift(); // removes first one, header
tableRows.forEach(row => {
var rowCols = row.getElementsByTagName('td');
var createdOnDate = rowCols[3];
var timeLimit = rowCols[7];
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
const createdDate = new Date(createdOnDate.innerText);
// if time limit is in days, remove text, & add to creation date-------------------//
var limitdays = timeLimit.innerText;
if (limitdays.includes(" days")) {
limitdays = limitdays.replace("days", "");
limitdays= parseInt(limitdays);
function addDaysToDate(createddate, days) {
var result = createddate;
result.setDate(createddate.getDate()+days);
return result;
}
var newDate = addDaysToDate(createdDate, limitdays);
// format newdate to iso & remove unwanted characters
newDate = newDate.toISOString();
if (newDate.includes("T")) {
newDate = newDate.replace("T", " ");
}
if (newDate.includes(".000Z")) {
newDate = newDate.replace(".000Z", "");
}
};
//===================================================================================//
// if time limit is in hours, remove text, & add to creation date-------------------//
// var limithours = timeLimit.innerText;
// if (limithours.includes(" hours")) {
// limithours = limithours.replace("hours", "");
// limithours= parseInt(limithours);
//
// function addHoursToDate(createddate, hours) {
// var result = createddate;
// // result.setHours(createddate.getDate()+6);
// return result;
// }
// var newDate = addHoursToDate(createdDate, limithours);
//
// // format newdate to iso & remove unwanted characters
// newDate = newDate.toISOString();
// if (newDate.includes("T")) {
// newDate = newDate.replace("T", " ");
// }
// if (newDate.includes(".000Z")) {
// newDate = newDate.replace(".000Z", "");
// }
// };
//===================================================================================//
const testRow = rowCols[8];
const timeDifference = func(newDate);
testRow.innerText = newDate;
});
}
loopThroughTableRows();
setInterval(loopThroughTableRows, 1000)
</script>

Given you have a creation date like "2022-04-15 17:47:19" and duration to expiry in the format "n [days|hours|minutes]", you probably want to do everything as local to avoid timezone issues. If you use Date objects, then it's simple represent it as a UTC timestamp using toISOString.
Consider the following, which returns a Date object for the expiry based on the creationDate and time limit. It does everything as local, so timezone and daylight saving issues are handled by the Date object. There's no validation of input, so that should be added.
// Parse YYYY-MM-DD HH:mm:ss as local
function parseISOLocal (ts) {
let [Y, M, D, H, m, s] = ts.split(/\D/);
return new Date(Y, M-1, D, H, m, s);
}
// Format a Date as YYYY-MM-DD HH:mm:ss
function formatISOLocal(date = new Date()) {
return date.toLocaleString('en-CA',{hour12: false}).replace(',','');
}
// Parse limit in "value [days|hours|minutes]" to {value, unit}
// e.g. "3 days" to {value: 3, unit:'day'}
function normaliseLimit(limit) {
let [value, unit] = limit.toLowerCase().split(/\s+/);
return {value: +value, unit: {d:'day', h:'hour', m:'minute'}[unit[0]]};
}
// Given:
// createdAt in YYYY-MM-DD HH:mm:ss format and
// limit as "number [days|hours|minutes]" return a Date for expiry
// I.e. createdAt plus limit
function getExpiryDate(createdAt, limitString) {
let expiry = parseISOLocal(createdAt);
let limit = normaliseLimit(limitString);
let method = {day:'Date', hour:'Hours', minute:'Minutes'}[limit.unit];
return new Date(expiry[`set${method}`](expiry[`get${method}`]() + limit.value));
}
let createdAt = formatISOLocal();
[{createdAt: createdAt, limit:'1 Day'},
{createdAt: createdAt, limit:'3 hours'},
{createdAt: createdAt, limit:'12 minutes'}
].forEach(({createdAt, limit}) => console.log(
`createdAt: ${createdAt}\n` +
`limit : ${limit}\n` +
`Expires : ${formatISOLocal(getExpiryDate(createdAt, limit))}`
));
Once you have the expiry date, you can work out the remaining time as days, hours, minutes, seconds as given at Difference between two dates in years, months, days in JavaScript and use it in a timer to show a count down, to work out which items have expired, etc.

Related

Date Format in Javascript(Indonesian Format) [duplicate]

How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?
You can create one with:-
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(5));
This takes care of automatically incrementing the month if necessary. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.
Correct Answer:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
Proof / Example
Check this JsFiddle
// Correct
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Bad Year/Month
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
// Bad during DST
function addDaysDstFail(date, days) {
var dayms = (days * 24 * 60 * 60 * 1000);
return new Date(date.getTime() + dayms);
}
// TEST
function formatDate(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}
$('tbody tr td:first-child').each(function () {
var $in = $(this);
var $out = $('<td/>').insertAfter($in).addClass("answer");
var $outFail = $('<td/>').insertAfter($out);
var $outDstFail = $('<td/>').insertAfter($outFail);
var date = new Date($in.text());
var correctDate = formatDate(addDays(date, 1));
var failDate = formatDate(addDaysWRONG(date, 1));
var failDstDate = formatDate(addDaysDstFail(date, 1));
$out.text(correctDate);
$outFail.text(failDate);
$outDstFail.text(failDstDate);
$outFail.addClass(correctDate == failDate ? "right" : "wrong");
$outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");
});
body {
font-size: 14px;
}
table {
border-collapse:collapse;
}
table, td, th {
border:1px solid black;
}
td {
padding: 2px;
}
.wrong {
color: red;
}
.right {
color: green;
}
.answer {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th colspan="4">DST Dates</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>03/10/2013</td></tr>
<tr><td>11/03/2013</td></tr>
<tr><td>03/09/2014</td></tr>
<tr><td>11/02/2014</td></tr>
<tr><td>03/08/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr>
<th colspan="4">2013</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2013</td></tr>
<tr><td>02/01/2013</td></tr>
<tr><td>03/01/2013</td></tr>
<tr><td>04/01/2013</td></tr>
<tr><td>05/01/2013</td></tr>
<tr><td>06/01/2013</td></tr>
<tr><td>07/01/2013</td></tr>
<tr><td>08/01/2013</td></tr>
<tr><td>09/01/2013</td></tr>
<tr><td>10/01/2013</td></tr>
<tr><td>11/01/2013</td></tr>
<tr><td>12/01/2013</td></tr>
<tr>
<th colspan="4">2014</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2014</td></tr>
<tr><td>02/01/2014</td></tr>
<tr><td>03/01/2014</td></tr>
<tr><td>04/01/2014</td></tr>
<tr><td>05/01/2014</td></tr>
<tr><td>06/01/2014</td></tr>
<tr><td>07/01/2014</td></tr>
<tr><td>08/01/2014</td></tr>
<tr><td>09/01/2014</td></tr>
<tr><td>10/01/2014</td></tr>
<tr><td>11/01/2014</td></tr>
<tr><td>12/01/2014</td></tr>
<tr>
<th colspan="4">2015</th>
</tr>
<tr>
<th>Input</th>
<th>+1 Day</th>
<th>+1 Day Fail</th>
<th>+1 Day DST Fail</th>
</tr>
<tr><td>01/01/2015</td></tr>
<tr><td>02/01/2015</td></tr>
<tr><td>03/01/2015</td></tr>
<tr><td>04/01/2015</td></tr>
<tr><td>05/01/2015</td></tr>
<tr><td>06/01/2015</td></tr>
<tr><td>07/01/2015</td></tr>
<tr><td>08/01/2015</td></tr>
<tr><td>09/01/2015</td></tr>
<tr><td>10/01/2015</td></tr>
<tr><td>11/01/2015</td></tr>
<tr><td>12/01/2015</td></tr>
</tbody>
</table>
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Be careful, because this can be tricky. When setting tomorrow, it only works because its current value matches the year and month for today. However, setting to a date number like "32" normally will still work just fine to move it to the next month.
These answers seem confusing to me, I prefer:
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day.
Hence, ms contains milliseconds for the desired date.
Using the millisecond constructor gives the desired date object.
My simple solution is:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);
this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);
is correct code.
Here is the way that use to add days, months, and years for a particular date in Javascript.
// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);
// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);
// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);
Try
var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000));
Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.
Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.
If you want to just simply add n days to the date you have you are best to just go:
myDate.setDate(myDate.getDate() + n);
or the longwinded version
var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);
This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.
The simplest approach that I have implemented is to use Date() itself.
`
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Reference: http://momentjs.com/docs/#/manipulating/add/
the simplest answer is, assuming the need is to add 1 day to the current date:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
To explain to you, line by line, what this code does:
Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
A solution designed for the pipeline operator:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
Usage:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
If you need more functionality, I suggest looking into the date-fns library.
Without using the second variable, you can replace 7 with your next x days:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
to substract 30 days use (24h=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=new Date();
var d = new Date(+yourDate - 30 *86400000)
console.log(d)
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
Short:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(newDate.getDate() + number));
}
console.log({
tomorrow: addDays(new Date(), 1)
});
Advance:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(date.getDate() + number));
}
function addMonths(date, number) {
const newDate = new Date(date);
return new Date(newDate.setMonth(newDate.getMonth() + number));
}
function addYears(date, number) {
const newDate = new Date(date);
return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}
function getNewDate(dateTime) {
let date = new Date();
let number = parseInt(dateTime.match(/\d+/)[0]);
if (dateTime.indexOf('-') != -1)
number = (-number);
if (dateTime.indexOf('day') != -1)
date = addDays(date, number);
else if (dateTime.indexOf('month') != -1)
date = addMonths(date, number);
else if (dateTime.indexOf('year') != -1)
date = addYears(date, number);
return date;
}
console.log({
tomorrow: getNewDate('+1day'),
yesterday: getNewDate('-1day'),
nextMonth: getNewDate('+1month'),
nextYear: getNewDate('+1year'),
});
With fix provide by jperl
Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment
As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000));
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
I had issues with daylight savings time with the proposed solution.
By using getUTCDate / setUTCDate instead, I solved my issue.
// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
// Make a working copy so we don't mutate the supplied date.
const d = new Date(date);
d.setUTCDate(d.getUTCDate() + num);
return d;
}
Why so complicated?
Let's assume you store the number of days to add in a variable called days_to_add.
Then this short one should do it:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to.
One day is 24h60min60s*1000ms = 86400000 ms or 864E5.
Generic prototype with no variables, it applies on an existing Date value:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
Sets the day of the month (1-31) for a specified date according to local time.
That is why I use setTime() when I need to add days.
I guess I'll give an answer as well:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance. (within reason, of course)
I was going to leave this as just comment under the Answer given by #AnthonyWJones but thought better of it.
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setTime( 864E5 * days + this.valueOf() ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setTime( 864E5 * days + date.valueOf() ) && date;
};
The above will respect DST. Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.
Example:
Nov 2, 2014 02:00 was the end of DST.
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 09:30:00
If you're looking to retain the time across DST (so 10:30 will still be 10:30)...
// Prototype usage...
Date.prototype.addDays = Date.prototype.addDays || function( days ) {
return this.setDate( this.getDate() + days ) && this;
};
// Namespace usage...
namespace.addDaysToDate = function( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
// Basic Function declaration...
function addDaysToDate( date, days ) {
return date.setDate( date.getDate() + days ) && date;
};
So, now you have...
var dt = new Date( 2014, 10, 1, 10, 30, 0 );
console.log( dt ); // Sat Nov 01 2014 10:30:00
console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 10:30:00

Time difference between an ISO 8601 date and now

I have a comment section on my website and each message have its created_at date time. After fetching it from the MariaDB database, I get a string like "2021-06-15T12:45:28.000Z" (ISO 8601). Then, I convert it to a "x minutes ago" text instead of the full date.
But then, I'm having some trouble when the date is parsed.
const epochs = [
["année", 31536000],
["mois", 2592000],
["jour", 86400],
["heure", 3600],
["minute", 60],
["seconde", 1]
];
function getInterval(timeAgo) {
for (let [ name, seconds ] of epochs) {
const interval = Math.floor(timeAgo / seconds);
if (interval >= 1) {
return { interval: interval, epoch: name };
}
}
}
function dateToString(d) {
const date = new Date(d);
console.log("Created at:", date);
console.log("Now:", new Date());
const timeAgo = Math.floor((new Date() - date) / 1000);
console.log("Time ago:", timeAgo);
const { interval, epoch } = getInterval(timeAgo);
const plural = (interval === 1 || epoch.slice(-1) === "s") ? "" : "s";
console.log("----------------------------");
return `Il y a ${interval} ${epoch}${plural}`;
}
dateToString("2021-06-15 12:45:28"); // Works fine
dateToString("2021-06-15T12:45:28.000Z"); // The "timeAgo" is negative
Subtracting the ISO date gives a negative number. I'm pretty sure this is a timezone problem because the
minimal value of the substraction is almost -7200 which is two hour and I'm in a UTC+2 timezone.
Have you any idea how can I fix this?
Thanks
Try adding or subtracting the timezoneOffset of the local computer from the UTC you get when you pass Z
I fixed your plural too
const epochs = {
"années": 31536000,
"mois": 2592000,
"jours": 86400,
"heures": 3600,
"minutes": 60,
"secondes": 1
};
const singular = {
"années": "ans",
"mois": "mois",
"jours": "jour",
"heures": "heure",
"minutes": "minute",
"secondes": "seconde"
};
const getInterval = timeAgo => {
const epoch = Object.entries(epochs).filter(([key, val]) => timeAgo >= val).shift();
const obj = {
epoch: epoch[0],
interval: parseInt(timeAgo / epoch[1])
}
if (obj.interval === 1) obj.epoch = singular[obj.epoch]
return obj
};
const aMinute = 60 * 1000
function dateToString(d) {
const date = new Date(d);
if (d.includes("Z")) {
let tzo = date.getTimezoneOffset();
tzo = (tzo > 0 ? tzo * -1 : tzo);
tzo *= aMinute
date.setTime(date.getTime() + tzo)
}
console.log("Created at:", date.toLocaleString());
console.log("Now:", new Date());
const timeAgo = Math.floor((new Date() - date) / 1000);
console.log("Time ago:", timeAgo);
console.log(getInterval(timeAgo))
const { epoch, interval } = getInterval(timeAgo);
console.log(epoch)
console.log("----------------------------");
return `Il y a ${interval} ${epoch}`;
}
console.log(
dateToString("2021-06-15 12:45:28"), "\n",
dateToString("2021-06-15T12:45:28.000Z"), "\n",
dateToString("2019-06-15T12:45:28.000Z"), "\n"
)

create date object by hours and minutes

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')
var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN
You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);
It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)

Get duration (in Hours and minutes) between two Date objects - JavaScript

Although, I've seen multiple similar questions here on SO but none of them could help me to figure out what's wrong with my calculation. I know I can use library such as Moment.JS to simplify my solution but I want native JavaScript only solution.
I'm trying to calculate duration (in hours and minutes) between two Date objects but I'm getting negative (incorrect) duration.
function padNumber(number, width = 2, padWith = '0') {
const strNum = number.toString();
return strNum.length >= width ? strNum : new Array(width - strNum.length + 1).join(padWith) + strNum;
}
// Get UTC date time from PHP date (Y-m-d) and time (H:i:s) strings
function getUTCDateTime(date, time, timezoneOffset = -480) {
const dateParts = date.split('-').map((el) => Number(el)); // Y-m-d
const timeParts = time.split(':').map((el) => Number(el)); // H:i:s
const dateTimeUTC = new Date(Date.UTC(dateParts[0], dateParts[1], dateParts[2], timeParts[0], timeParts[1], timeParts[2]));
// Set back Singapore specific time (GMT+8:00)
dateTimeUTC.setUTCHours(dateTimeUTC.getUTCHours() + timezoneOffset / 60);
return dateTimeUTC;
}
function getDuration(timeStart, timeEnd = new Date()) {
const msDiff = timeEnd.getTime() - timeStart.getTime();
const minDiff = msDiff / 60000;
const hourDiff = Math.floor(msDiff / 3600000);
return {
hours: this.padNumber(hourDiff, 2),
minutes: this.padNumber(Math.floor(minDiff - 60 * hourDiff), 2)
};
}
// Got from server (in Singapore timezone)
const serverDate = '2018-10-18';
const serverTime = '00:22:51';
// Convert server date and time (timezone specific) strings to Date object
const serverUTC = getUTCDateTime(serverDate, serverTime);
// Get duration between server time and now
const duration = getDuration(serverUTC);
// Expected positive value but getting negative as server time is in past
console.log(duration);
I expected positive value in console log but I'm getting negative. Have I missed anything?
The problem stems from the fact that months are zero-based in JavaScript (i.e. January is 0, February is 1, and so on). Your date construction in getUTCDateTime() doesn't take this into account.
This line:
const dateTimeUTC = new Date(Date.UTC(dateParts[0], dateParts[1], dateParts[2], timeParts[0], timeParts[1], timeParts[2]));
Should be:
const dateTimeUTC = new Date(Date.UTC(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]));
Complete snippet:
function padNumber(number, width = 2, padWith = '0') {
const strNum = number.toString();
return strNum.length >= width ? strNum : new Array(width - strNum.length + 1).join(padWith) + strNum;
}
// Get UTC date time from PHP date (Y-m-d) and time (H:i:s) strings
function getUTCDateTime(date, time, timezoneOffset = -480) {
const dateParts = date.split('-').map((el) => Number(el)); // Y-m-d
const timeParts = time.split(':').map((el) => Number(el)); // H:i:s
const dateTimeUTC = new Date(Date.UTC(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]));
// Set back Singapore specific time (GMT+8:00)
dateTimeUTC.setUTCHours(dateTimeUTC.getUTCHours() + timezoneOffset / 60);
return dateTimeUTC;
}
function getDuration(timeStart, timeEnd = new Date()) {
const msDiff = timeEnd.getTime() - timeStart.getTime();
const minDiff = msDiff / 60000;
const hourDiff = Math.floor(msDiff / 3600000);
return {
hours: this.padNumber(hourDiff, 2),
minutes: this.padNumber(Math.floor(minDiff - 60 * hourDiff), 2)
};
}
// Got from server (in Singapore timezone)
const serverDate = '2018-10-18';
const serverTime = '00:22:51';
// Convert server date and time (timezone specific) strings to Date object
const serverUTC = getUTCDateTime(serverDate, serverTime);
// Get duration between server time and now
const duration = getDuration(serverUTC);
// Expected positive value but getting negative as server time is in past
console.log(duration);

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

Categories

Resources