How to format $.now() with Jquery - javascript

$.now() gives me the time as miliseconds. I need to show it something like hh:mm:ss
How can I do that in Jquery?

I'd suggest just using the Javascript Date object for this purpose.
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
Edit: I just came across the method below, which covers formatting issues such as the one mike-samuel mentioned and is cleaner:
var time = d.toLocaleTimeString();

function formatTimeOfDay(millisSinceEpoch) {
var secondsSinceEpoch = (millisSinceEpoch / 1000) | 0;
var secondsInDay = ((secondsSinceEpoch % 86400) + 86400) % 86400;
var seconds = secondsInDay % 60;
var minutes = ((secondsInDay / 60) | 0) % 60;
var hours = (secondsInDay / 3600) | 0;
return hours + (minutes < 10 ? ":0" : ":")
+ minutes + (seconds < 10 ? ":0" : ":")
+ seconds;
}

JSFiddle example here
http://jsfiddle.net/NHhMv/
The jquery now is nothing but
The $.now() method is a shorthand for the number returned by the expression
(new Date).getTime().
from jquery
http://api.jquery.com/jQuery.now/
and follow this link
Where can I find documentation on formatting a date in JavaScript?

new Date().toString().split(' ')[4]
or
new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]
The toString method is basically an alias for toLocaleString in most implementations. This will return the time in the user's timezone as opposed to assuming UTC by using milliseconds if you use getTime (if you use getMilliseconds you should be OK) or toUTCString.

I'd suggest date-format jQuery plugin. Like this one or this one (I am using the former)

I'm way late to this, but thought i'd just throw this little snippet out there for the masses. This is something I use just to get a quick localized timestamp. It's pretty clean and handy.
function getStamp() {
var d = new Date();
var mm = d.getMilliseconds(), hh = d.getHours(),
MM = d.getMinutes(), ss = d.getSeconds();
return (hh < 10 ? "0" : "") + hh + (MM < 10 ? ":0" : ":") + MM + (ss < 10 ? ":0" : ":") + ss + ":" + mm;
};

jQuery doesn't have date formatting. You can roll your own with the JavaScript Date object, or you can use a library that does it for you. DateJS is one such library, which provides a rich set of formatting, parsing, and manipulation functionality. However, it hasn't been maintained in years. momentjs is under active development.

Related

Extract time from JS Date object without offsetting the Time zone

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));

Difference Between 2 Timestamps using javascript without using moment.js

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

Best way to convert a unix timestamp to javascript date-time

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

Is there a way to directly format the time in Javascript?

What I want it is to get the output of the current time with Javascript. The output should be something similar as:
15:28:30 PM
And I got this using the following code:
var date = new Date();
document.write("Current time: " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
if (date.getHours() <= 12)
document.write(" AM");
else
document.write(" PM");
So the output that I get it is:
Current time: 3:0:16 AM
But I want to know if there is some faster or cleaner solution to solve this problem because I think my solution it is not good at all.
Is it possible to get the same behaviour with a better method or solution?
Thanks in advance!
var date = new Date();
var time = date.toLocaleString('en').split(', ').pop();
This will give you the exact format you are looking for. Although I would go with a library like Moment.js or Date.js. Tons of options with those.
It's like this:
var dt = new Date;
console.log(dt.toLocaleTimeString());
I see nothing wrong with your approach. However, if you want the flexibility of different formats, there's a library called moment.js which allows you to build and format dates.
moment().format('hh:mm:ss A'); // 12:00:00 AM
I think that you make right way. Only need modify a little to get your expectation:
var date = new Date();
int hour = date.getHours();
string abbr;
if (date.getHours() <= 12)
abbr = " AM";
else {
hour = hour + 12;
abbr = " PM";
}
document.write("Current time: " + hour + ":" + date.getMinutes() + ":" + date.getSeconds() + abbr);
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
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
Found this thread

hour format in javascript

In my javascript iam using GetHour and GetMinutes function.For eg:Current Time is 2:03.If in this case i use GetHour(),it returns 2.Instead i need 02.Can anybody help?
var hour = GetHour() < 10 ? '0' + GetHour() : GetHour();
var d,h
d = new Date()
h = (h = d.getHours()) < 10 ? '0' + h : h
The obvious answer is to use an IF statement...
var dat = new Date();
var hr = dat.getHour();
if(hr < 10) {
hr = "0" + hr;
}
You could always just do
var time = new Date();
('0' + time.getDate()).slice(-2)
There's a javascript library here which looks like it will handle all sorts of date conversions nicely, including formatting dates so that the month is always two digits.
If you use the Prototype framework there's a toPaddedString method that does this.
a = 2;
a.toPaddedString(2)
// results in "02"
There is no function for that.
Use the following to add a leading 0:
var date = new Date();
var hours = new String(date.getHours());
if (hours.length == 1)
{
hours = "0" + hours;
}

Categories