Converting unix timestamp into time - javascript

So I want to convert unix timestamp into date time object, I am trying to do this with :
async function getTime(unix){
var date = new Date(unix * 1000);
var hours = date.getHours();
var mins = "0" + date.getMinutes();
var secs = "0" + date.getSeconds();
var formattedTime = hours + ':' + mins.substr(-2) + ':' + secs.substr(-2);
}
but I keep getting
Promise { undefined }
on the table. can someone please tell me how to fix this?

So far as I can see your function, you don't return anything. You have to return the variable that you want. Also, there are no async calls within this function so it seems useless to make this an async function.
To add to this, the variable you want to return is probably formattedTime.
function getTime(unix) {
const date = new Date(unix * 1000);
const hours = date.getHours();
const mins = "0" + date.getMinutes();
const secs = "0" + date.getSeconds();
return hours + ':' + mins.substr(-2) + ':' + secs.substr(-2);
}
Please note: I am using const, may that not be possible to use, use var instead.

Related

Get System time, localstorage, compare dates and performe an action

I need to get the system time once, then store it on localStorage, then compare this stored value with a further system date and then perform an action if the future date is equal or greater than the one which is stored. I have tried but I am stucked in making the function which gets the system time the first time to run only once so I can get a future date to compare.
This is my code
console.log(formatTime());
function formatTime() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
return (strTime = date.getDay() + "/" + date.getMonth() + "/" + date.getFullYear() + " " + hours + ":" + minutes + ":" + seconds + " " + ampm);
}
document.getElementById("currentdt").innerHTML = strTime;
var strTime1 = formatTime();
var timeString = JSON.stringify(strTime1);
localStorage.setItem("strTime1", timeString);
var timeStringFromLocalStorage = localStorage.getItem("strTime1");
var timeFromLocalStorage = JSON.parse(timeStringFromLocalStorage);
document.getElementById("time").innerHTML = strTime1;
console.log(timeStringFromLocalStorage);
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA, "strTime1");
var momentB = moment(dateTimeB, "strTime");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("strTime1", "strTime"));
The function below will check if there has been a value set in localStorage. If there is no value set, it will set its first and stop the function.
If there is a value, then it will be turned into a moment instance and compared with the current date. If a difference in days is equal or larger to than specified it will redirect the page.
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
/**
* If nothing is stored yet, then storedValue will be null.
* Here you will set the first localStorage item for the first time.
* Instead of a full date, store the timestamp.
* Then stop the function.
*/
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
/**
* If there is a stored value then it will be a timestamp as a string.
* First parse it into a number before putting it into moment.
* Then check the difference in days between the dates.
*/
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
/**
* If the difference is higher or equal to the given days, redirect.
*/
if (difference >= days) {
location.href = url;
}
}
Call the function with amount of days that should have passed since the first visit and the URL to redirect to.
redirectWhenOlderThan(15, 'https://example.com');
I hope this is what you meant.
Sidenote: dive into moment.js if you have the time. It has a lot of features that could spare you some time, like your formatTime() function, it can be written in a single line with moment.
moment().format('DD/MM/YYYY h:mm:ss A');
Now the final code goes like this
function formatTime() {
var date = new Date();
return strTime = date.getDay() + '/' + date.getMonth()+'/'+date.getFullYear();
}
document.getElementById("currentdt").innerHTML = strTime;
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
if (difference >= days) {
location.href = url;
}
else {
window.location.href= 'app/phr.html';
}
}
setTimeout(function () {
redirectWhenOlderThan(1, 'app/licences.html');
}, 3000);

Javascript add hours to time

I have this javascript code which should show the time. It works. I wan't to be able to add extra time though. Lets say that I want to add 1 hour.
<script type="text/javascript">
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
// This function gets the current time and injects it into the DOM
function updateClock() {
// Gets the current time
var now = new Date();
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Format hours, minutes and seconds
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds;
}
function start(){
setInterval('updateClock()', 200);
}
</script>
The first function calculates the milisecons that I want to add, and the second function is the "live clock". How do I implement the first function into the second one, so I get the working result?
for adding hours, use setHours :
// Gets the current time
var now = new Date();
console.log("actual time:", now);
now.setHours(now.getHours() + 1)
console.log("actual time + 1 hour:", now);
For references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
Check out this fiddle.
The constructor Date(milliseconds) of class Date can be used here.
Here is the snippet.
var now = new Date();
alert(now);
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
Check out this
fiddle here
var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );
javascript date API is near to be completed, the existing methods of it can be use to add another functionality for this API, some says it is tedious but its not.
in order to add a method in a date we will access the prototype of this API,
like this.
Date.prototype.addTime = function(str){
function parse(str){
let arr = (typeof str == 'number')?[str]:str.split(":").map(t=>t.trim());
arr[0] = arr[0] || 0;
arr[1] = arr[1] || 0;
arr[2] = arr[2] || 0;
return arr
}
function arrToMill(arr){
let [h,m,s] = arr;
return (h*60*60*1000) + (m*60*1000) + (s*1000);
}
let date = new Date(this.getTime());
let parsed = parse(str);
date.setTime(date.getTime() + arrToMill(parsed));
return date;
}
getting it rockin.
this function is immutable
let date = new Date();
date.addTime(1);
date.addTime("01:00");`

How to show current time in JavaScript in the format HH:MM:SS?

How do I show the current time in the format HH:MM:SS?
You can use native function Date.toLocaleTimeString():
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
MDN: Date toLocaleTimeString
var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<div id="time"></div>
DEMO using javaScript only
Update
Updated Demo
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
You can do this in Javascript.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
You can use moment.js to do this.
var now = new moment();
console.log(now.format("HH:mm:ss"));
Outputs:
16:30:03
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM.
Use this way:
var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });
Result: 18:56:31
function realtime() {
let time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
}, 1000)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
A very simple way using moment.js and setInterval.
setInterval(() => {
moment().format('h:mm:ss a');
}, 1000)
Sample output
Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.
3:25:50 pm
This is how I use this method on one of my side projects.
setInterval(() => {
this.time = this.shared.time;
}, 1000)
Maybe you're wondering if using setInterval() would cause some performance issues.
Is setInterval CPU intensive?
I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday
No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth
But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy
new Date().toLocaleTimeString('it-IT')
The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01
Compact clock function:
setInterval(function() {
let d = new Date()
console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
new Date().toLocaleTimeString()
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
Use
Date.toLocaleTimeString()
// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠
Source

Format a time string with zero based hours and minutes in javascript

This is what have tried:
partly pseudocode:
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;
Is there a smarter way like a formatted string function where I can say:
var minutes = date.getMinutes('mm');
var hours = date.getHours('hh');
so it adds the zeros automatically ?
Here is your code fixed since there is no length on an integer
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours<10) hours = "0" + hours;
if (minutes<10) minutes = "0" + minutes;
var time = ""+ hours + ":" + minutes;
You do not need a framework and there is no shorter way to do this
This may be what you mean:
Live demo
function pad(num) {
return ("0"+num).slice(-2)
}
var time = pad(date1.getHours())+":"+pad(date2.getMinutes());
This functionality doesn't exist natively in javascript, you have to either add it yourself (as you have started to do), or, use a package.
moment
Mozilla has an example
Here's a blog post to a date formatting function
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Use DateJS and you will be able to use mm and hh to add the preceding zeros :)
https://code.google.com/p/datejs/wiki/FormatSpecifiers
You can add a method to Number prototype
Number.prototype.pad0 = function(length) {
var result = this.toString();
while(result.length<length) result = "0"+result;
return result;
}
Then you can get what you want
var date = new Date();
console.log(date.getMinutes().pad0(2));
console.log(date.getHours().pad0(2));
Yet another way of doing it:
var d = new Date();
var t = [ d.getHours(), d.getMinutes(), d.getSeconds() ];
var s = t.map( function(z){return ('00'+z).slice(-2)} ).join(':');
console.log(s);
Time parts are put into an array. That array goes through map() where the numbers get leading zeros. The resulting array is then joined into a string with the ":" separator.
Convert numbers to strings before you check the lengths:
var hours = String(date1.getHours());
var minutes = String(date2.getMinutes());
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;

Make clock running

I would like the time to reset every second so the clock becomes a running one. I'm a javascript noob and I couldn't find any solution anywhere.
<!--
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
//-->
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
document.write(hours + ":" + minutes + ":" + seconds)
var myInterval = window.setInterval(function() {
window.document.write(hours + ":" + minutes + ":" + seconds);
}, 1000);
Later you can stop it with
window.clearInterval(myInterval);
We assign the return value of setInterval (an ID in the form of a number) to a variable because we'll need it later to stop our particular interval using the clearInterval function. If we don't do that, there will be no way (without certain hacks) to stop the interval.
For that you need to use the window.setInterval method. Please look at this page for more information: http://www.w3schools.com/js/js_timing.asp

Categories

Resources