Reputation: 495
I have a variable that contains timestamp value that I have calculated first. I need to convert timestamp variable in a date and put the date in my:
<input type="date" id="topic_date">
Anyone can help me?
Upvotes: 2
Views: 3758
Reputation: 1
You might consider extending the Number object
if (!Number.prototype.epochToTime) {
Number.prototype.epochToTime = function() {
const time = (this * 1000);
function pad(n) {
return n < 10 ? '0' + n : n;
}
const date = new Date(time);
return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
};
}
Upvotes: 0
Reputation: 1895
@jedifans We can use padStart() to format the number. And the month value starts from 0, so we should add 1 to the month value. The full code is like below:
const lpad2 = (number) => String(number).padStart(2, "0")
function timeStampToDate(timestamp) {
let date = new Date(timestamp * 1000)
return (
date.getFullYear() + "-" + lpad2(date.getMonth() + 1) + "-" + lpad2(date.getDate())
)
}
Upvotes: 0
Reputation: 316
Datetime doesn't work for me on chrome, datetime-local allows me to choose date and time from popup.
example
<input type="datetime-local" name="xyz" value="<?php echo date("Y-m-d\TH:i:s",time()); ?>"/>
time() functions is not relevant ,I am using it to make it easy for user to choose from current.. time after or before.
Upvotes: 0
Reputation: 2297
Try the following, parsing the timestamp into a date object first, after converting to milliseconds from seconds:
function lpad(str, length) {
var lengthDiff = length - str.length;
while(lengthDiff > 0) {
str = '0' + str;
lengthDiff--;
}
return str;
}
var parsedTimestamp = new Date(timestamp * 1000);
document.getElementById('topic_date').value = parsedTimestamp.getFullYear() + '-' + lpad(parsedTimestamp.getMonth(), 2) + '-' + lpad(parsedTimestamp.getDate(), 2);
Upvotes: 3