I am looking for a way to convert a javascript Date to a number that represents the amount of days passed since , for example, 1.1.1900, for that date. As it is usually done with timestamps and miliseconds.
Can I do this?
You can achieve this by using the javascript function getTime().
Code:
var a = new Date();
alert(a.getTime());
Working Example
According to getTime() definition:
The getTime() method returns the numeric value corresponding to the
time for the specified date according to universal time.
More can be found in this link
UPDATE:
If you want to have it in no of days then you would need to calculate it or use library like moment.js
Working Fiddle for Days
For example something like:
var date1 = new Date("1/Jan/1900 00:00:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");
Related
I'm trying to get a dynamic date from a span with the id datetime and use that date for a countdown timer. But I see Nan all the time
<span id="datetime">30.11.2022 08:50:00</span>
<p id="demo"></p>
<script>
var enddateTime = document.getElementById('datetime').textContent;
// Set the date we're counting down to
var countDownDate = new Date(enddateTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
I tried using .textContent to get the field value
var enddateTime = document.getElementById('datetime').textContent;
Everything is fine in the console, but when I use in the timer script, I get NaN
const newDate = new Date('30.11.2022 08:50:00');
console.log(newDate); // Invalid Date
Your date format is simply invalid. Try for example using '2022-11-30 08:50:00' as your date.
<span id="datetime">2022-11-30 08:50:00</span>
More here.
<span id="datetime">30.11.2022 08:50:00</span>
This value inside HTML element is invalid format date in Js.
You should change the value to 2022-11-30 08:50:00. This is YYYY-MM-DD HH:mm:ss Date format in js.
I have implemented the code below in my site, to display a running timer. The site is running on Wordpress. At the moment the date is input in the code (so it applied site wide). I am looking to have a running timer on each post.
I need to change the code below so that I can use a custom field on each post called "expiry" as the date, instead of the hardwired date below (newDate("Jan 5, 2021 15:37:25).getTime()
<!-- Display the countdown timer in an element -->
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
The above code is sourced from here
My site is here
Thanks in advance
below steps is your requirements:
1) in custom field expiry set return format as custom "F j, Y g:i:s"
example link (https://prnt.sc/pqg79l)
2) add this function in functions.php
function functionname() {
global $post;
$field= get_field('expiry_date', $post->ID);
echo '<input type="hidden" id="date" value="'.$field.'">';
}
add_action( 'template_redirect', 'functionname' );
3) in your js file add below script
var $= jQuery;
var d = $("#date").val();
console.log(d);
// Set the date we're counting down to
var countDownDate = new Date(d).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
make sure you have to add <p id="demo"></p> where you want to show in post
I have tried this code..It's totally working fine..I hope i have helped you by this
here is my script
var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
var countDownDate = new Date(specialDate).getTime();
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var countdown = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
the above code is working perfectly fine on all the browsers except for safari.
after googling I came to know I need to convert this to iso 8601 compliant to work for safari (currently it is showing nand nanh nanm nans error on safari browser iphone 6 )
I is the detail of of my phone
EDIT:
here is page source
try changing the following:
var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
var countDownDate = new Date(specialDate).getTime();
To:
// echo php timestamp
var specialDate = <?php echo strtotime($time[1]);?>;
// multiply by 1000 for equivalent of `Date.getTime()`
var countDownDate = specialDate * 1000;
So i was looking for a function to get the timespan between two dates and i've found this answer on SO
Work with a time span in Javascript
However the date is in this format 7/Nov/2012 20:30:00 and my dates are 7/11/2012 20:30:00, and my values came from inputs
http://jsbin.com/igaruj/47/edit
If a try to change "Nov" to "11" i got NaN on the output. Do i have to convert the dates ?
Here is the code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<input type="text" id ="start"value="7/Nov/2012 20:30:00" />
<input type="text" id="end" value="20/Nov/2012 19:15:00" />
</body>
</html>
The javascript
var startDate = document.getElementById("start").value;
var endDate = document.getElementById("end").value;
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
With your 20/11/2012 20:30:00 date format:
var startDate = "7/11/2012 20:30:00";
var endDate = "20/11/2012 19:15:00";
You're getting the NaN because, it wants it in the format mm/dd/yyyy. So 20 is ofcourse an invalid month.. interchange the month and day values like:
var parts = startDate.split('/');
startDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/7/2012 20:30:00
var parts = endDate.split('/');
endDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/20/2012 9:15:00
and then do your normal time diff work and it will work:
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
alert(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
//12 days 22 hours 45 minutes 0 seconds
See the DEMO here
Use JavaScript's Date and simply call new Date("7/Nov/2012 20:30:00") to get a JS Date object. Then you could extract the day, month and year using methods on that Date object.
I am building an Instagram feed with JQuery into my site and want to show how long has passed since the post was submitted in a short form like: 23H or 2D or 3M or 1Y depending on how long its been. I've got my two date objects but I can't figure our how to calculate the difference and display it how i want.
I am fairly new to JS/Jquery and as far as i could get was:
var pd = new Date(postDate);
var nd = new Date();
var nd = nd.getTime();
var difference = nd-pd;
How do I calculate the difference between two dates in hours, days, months and years?
Thanks.
Doing anything with dates is generally painful.
If you aren't committed to using that exact format, you can use a library for this instead.
moment.js has a .fromnow() function.
or timeago.js can be used to update the element on the page periodically, so if the user leaves the page open for a few minutes, the time stamps will count up.
You can do this to get the time elapsed since posted
var timeDiff = Math.abs(nd.getTime() - pd.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
you can try like this.
var pd = new Date(postDate);
var nd = new Date();
var Hours = nd.getHours() - pd.getHours();
var Days = nd.getDay() - pd.getDay();
var Months = nd.getMonth() - pd.getMonth();
var Years = nd.getYear() - pd.getYear();
or get millisecods diference
var miliseconds = (nd - pd).getTime(); //gets time in miliseconds since 1/1/1970
then use your logic to calculate hours, days, months and years
you can have a look at this Work with a time span in Javascript
moments
ar date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
My solution is dirty but direct: calculate them by myself.
Record start time:
var BEGIN_TIME=new Date();
var HOUR=BEGIN_TIME.getHours();
var MINUTE=BEGIN_TIME.getMinutes();
var SECOND=BEGIN_TIME.getSeconds();
Then do so some math
var today=new Date();
h=today.getHours();
m=today.getMinutes();
s=today.getSeconds();
s = s - SECOND;
if (s<0) { s=s+60; m=m-1; }
m = m - MINUTE;
if (m<0) { m=m+60; h=h-1; }
h = h - HOUR;