I have been following Convert a Unix timestamp to time in JavaScript thread for answer but looks like single digit time (0-9) is parsed as it is. The accepted answer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
We get like 2:3:9 instead of 02:03:09. How to get rid of this behaviour? Also can anyone please elaborate on how to get am/pm along with time?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
I think I will leave the am:pm bit to you. Press ctrl-shift j and play with your code in the console right here
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
This might be easier to understand. I have kept it closer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
I think you have to get rid of the substr-part, since the value should already be correct.
Note: you need to check if the values are already above 9, because you don't need to append anything when it is above 9.
Example
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
I want to add that these kinds of problems can be easily resolved with using a good library like moment.js
Related
suppose if time now is 13:36:22 , I want array of past 5 minutes like this
2019-05-07T13:36:00+0530
2019-05-07T13:35:00+0530
2019-05-07T13:34:00+0530
2019-05-07T13:33:00+0530
2019-05-07T13:32:00+0530
I tried something like below to get past 5 minutes by , but dont know how to remove seconds and to get to that format
var now = new Date();
now.setSeconds(0);
var last1 = new Date(today.getTime() - (1000*60));
var last2 = new Date(today.getTime() - (1000*120));
var arr = [last1,last2,..and so on];
but its also returning some seconds like Tue May 07 2019 13:40:57 , I want to remove seconds and also am looking for this format
2019-05-07T13:32:00+0530
You should construct the format yourself, unless you want to use an external library.
First define your timezone offset so you can add it to UTC timestamp returned by Date.now(). Then set s and ms to 0 and build your desired date format. Also added the leading 0 for month, day and so on, which is removed by slice when the number is already double digits.
let offset = 5.5;
let now = Date.now() + offset*60*60*1000;
date = new Date(now);
date.setSeconds(0, 0);
let timezone = Math.floor(offset) === offset ?
"0" + offset + "00" :
"0" + Math.floor(offset) + "30"
dateString = date.getFullYear() +"-"+
("0" + (date.getMonth()+1)).slice(-2) +"-"+
("0" + date.getDate()).slice(-2) +"T"+
("0" + date.getHours()).slice(-2) +":"+
("0" + date.getMinutes()).slice(-2) +":"+
("0" + date.getSeconds()).slice(-2) +"+"+
timezone;
console.log(dateString);
So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:
"2017-12-29T20:00:00"
What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:
"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.
Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:
function reformatTimestamp(s) {
function z(n){return (n<10?'0':'')+ +n}
var b = s.split(/\D/);
var h = b[3]%12 || 12;
var ap = b[3] < 12? 'AM':'PM';
return b[1] + '/' + b[2] + '/' + b[0] +
' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}
console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM
I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).
Use this code:
function formatAMPM(date) {
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
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;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var str = "2017-12-29T20:00:00";
var dt = new Date(str + "Z");
console.log("M/d/yyyy");
console.log((dt.getUTCMonth() + 1) + '/' + dt.getUTCDate() + '/' + dt.getUTCFullYear());
console.log("hh:mm AM/PM");
console.log(formatAMPM(dt));
I have 2 timestamps
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
I need the difference between these timestamps in hours and minutes using javascript but without using moment.js.
Means the output should in hours and minutes like for ex:(02h 13min).
Do provide some more context or in depth information of the solution you have up to now. That said, I understand the need/question of your second part "hours/minutes/seconds"; below is some context on that, or read up on it at milliseconds to time in javascript.
That being said,
You could just either try subtracting, as in end - start.. as in following code example.
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
document.write(endTimestamp - startTimestamp + '<br/>');
This will output 812041 - which are the milliseconds.
If you want to convert those milliseconds to the known format of hh:mm:ss.ms you can try the following code by example - also on jsfiddle.
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
document.write(endTimestamp - startTimestamp + '<br/>');
document.write(millisecondsToHoursMinutesSeconds(endTimestamp - startTimestamp));
document.write('<hr/>');
function millisecondsToHoursMinutesSeconds(ms) {
var milliseconds = parseInt((ms%1000)/100)
, seconds = parseInt((ms/1000)%60)
, minutes = parseInt((ms/(1000*60))%60)
, hours = parseInt((ms/(1000*60*60))%24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
Or read other solutions in this question: milliseconds to time in javascript
I use Date object to create time in my Javascript code and it should be formated like so : 08:04:21. This is how I tried to do it:
$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});
But when Time is logged in console string looks like this 8:1:1467844916075. Same happens when i try this:
var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();
It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object
$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});
But Time in this case looks like this: 1467785566719. Any idea how to get human readable current time(not date) plus one minute?
You can check this:
Date.getTime() returns you the number of milliseconds since 1970/01/01.
So just grab it and add 1 minute to it to form new milliseconds count for new date.
var d = new Date();
var millisecondssince1970 = d.getTime();
var newMillisec = millisecondssince1970 + (1000 * 60);
var newDate = new Date(newMillisec);
console.log(newDate.getHours() + ":"
+ newDate.getMinutes() + ":"
+ newDate.getSeconds());
Please try this,
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Here is working example https://jsfiddle.net/oa7j3krs/2/
$('#time').click(function(){
var d = new Date($.now()+60*1000); // current time + 60s
$(this).val(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
});
Anyway, I found a way to do this. Maybe it's not the best but it will do the job.
$('#time').click(function(){
var currentTime = new Date();
var addOneMinute = currentTime.getMinutes();
addOneMinute=parseInt(addOneMinute) + 1;
var Time=currentTime.getHours() + ":"
+ addOneMinute + ":"
+ currentTime.getSeconds();
console.log(Time);
$(this).val(Time);
});
I get the time from the database in Unix format.
It looks like this: console.log (time);
Result: 1300709088000
Now I want to reformat it and pick out only the time, I found this: Convert a Unix timestamp to time in JavaScript
That did not work as I want. The time I get is this:
1300709088000
9:0:0
1300709252000
6:33:20
1300709316000
0:20:0
1300709358000
12:0:0
1300709530000
11:46:40
It is very wrong times when I know that times are quite different. How can I fix it?
console.log(time);
var date = new Date(time*1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes + ':' + seconds;
console.log(formattedTime);
It looks like this: console.log (time); Result: 1300709088000
That doesn't look like a Unix timestamp (seconds since The Epoch), it looks like milliseconds since The Epoch. So you wouldn't multiply by 1000 to convert from seconds to milliseconds for JavaScript, it's already in milliseconds (or you're dealing with dates more than 41,000 years from now; which is fair enough).
Test:
var times = [
1300709088000,
1300709252000,
1300709316000,
1300709358000,
1300709530000
];
var index;
for (index = 0; index < times.length; ++index) {
display(times[index] + " => " + new Date(times[index]));
}
Live copy
Update: Or getting the individual parts:
var times = [
1300709088000,
1300709252000,
1300709316000,
1300709358000,
1300709530000
];
var index, dt;
for (index = 0; index < times.length; ++index) {
dt = new Date(times[index]);
display(times[index] +
" => " +
dt +
" (" + formatISOLikeDate(dt) + ")");
}
// Not all implementations have ISO-8601 stuff yet, do it manually
function formatISOLikeDate(dt) {
var day = String(dt.getDate()),
month = String(dt.getMonth() + 1), // Starts at 0
year = String(dt.getFullYear()),
hour = String(dt.getHours()),
minute = String(dt.getMinutes()),
second = String(dt.getSeconds());
return zeroPad(year, 4) + "-" +
zeroPad(month, 2) + "-" +
zeroPad(day, 2) + " " +
zeroPad(hour, 2) + ":" +
zeroPad(minute, 2) + ":" +
zeroPad(second, 2);
}
function zeroPad(str, width) {
while (str.length < width) {
str = "0" + str;
}
return str;
}
Live copy ...but if you're going to be doing much of anything with dates, I'd look at DateJS.
Your time stamps are not in Unix format, they're already in the Javascript millisecond resolution format.
Hence you shouldn't be multiplying by 1000 when you create your Date object.
I've tried to do something like this:
console.log (time);
where date = new Date (time);
/ / hours party from the timestamp
was hours = date.getHours ();
/ / party minutes from the timestamp
Every minute = date.getMinutes ();
/ / Seconds Party From The timestamp
where seconds = date.getSeconds ();
/ / Will display time up 10:30:23 format
was formattedTime = hours + ':' + minutes + ':' + seconds;
console.log (formattedTime);
The result is this:
1300709088000
NaN: NaN: NaN