I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM
or 10.00 PM
.
Is there a jQuery function that is able to do this?
Please help.
Thanks
DateTimePicker allows you to define the text representation of a date and time value to be displayed in the DateTimePicker control. The format specified is achieved by the dateTimeFormat property. Default value of this property is M/d/yyyy h: mm tt.
There is Date object in pure javascript, no jQuery needed. http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
Date
object, using the getHours()
and getMinutes()
functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").To use just about any of those, first you have to turn that "milliseconds" value into a Date
object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10)
and then use new Date(num)
to create the Date
object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10))
gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000)
gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date()
to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With