I'm using Angularjs and would like to know how can I display a date in this "format"
member for : 1 year, 10 months
Is there a Javascript/Jquery/Angularjs built-in function that is doing it or should I calculate it myself.
Thank you
You could create your own filter which wraps .fromNow() in moment.js.
filter('timeago', function() {
return function(datetime) {
return moment(datetime).fromNow();
};
})
Then you can use it like any other angular filter;
{{ "2014-01-01T12:00:00" | timeago }}
Demo
Since I didn't find exactly what I was looking for I did it myself.
So this function returns the time passed between two dates.
Date.prototype.from = function(pastDate, presentDate){
var presentDate = (typeof presentDate === "undefined") ? this : presentDate;
//the string to return.
var dateString = "";
var minute = 60 * 1000,
hour = minute * 60,
day = hour * 24,
month = day * 30,
year = month * 12,
ms = Math.abs(presentDate - pastDate);
var years = parseInt(ms / year, 10);
ms -= years * year;
var months = parseInt(ms / month, 10);
ms -= months * month;
var days = parseInt(ms / day, 10);
ms -= days * day;
var hours = parseInt(ms / hour, 10);
ms -= hours * hour;
var minutes = parseInt(ms / minute, 10);
if(months <= 0 && days <= 0 && hours <= 0 && minutes <= 0){
dateString = "1 minute";
return dateString;
}
if(years > 0){
if(years == 1){
dateString += years + " year";
}else{
dateString += years + " years";
}
if(months > 0){
if(months == 1){
dateString += ", " + months + " month";
}else{
dateString += ", " + months + " months";
}
}
//year = 0
}else{
if(months > 0){
if(months == 1){
dateString += months + " month";
}else{
dateString += months + " months";
}
if(days > 0){
if(days == 1){
dateString += ", " + days + " day";
}else{
dateString += ", " + days + " days";
}
}
//month = 0
}else{
if(days > 0){
if(days == 1){
dateString += days + " day";
}else{
dateString += days + " days";
}
if(hours > 0){
if(hours == 1){
dateString += ", " + hours + " hour";
}else{
dateString += ", " + hours + " hours";
}
}
//days = 0
}else{
if(hours > 0){
if(hours == 1){
dateString += hours + " hour";
}else{
dateString += hours + " hours";
}
if(minutes > 0){
if(minutes == 1){
dateString += minutes + " minute";
}else{
dateString +=", " + minutes + " minutes";
}
}
//hours = 0
}else{
if(minutes > 0){
if(minutes == 1){
dateString += minutes + " minute";
}else{
dateString += minutes + " minutes";
}
}
}
}
}
}
return dateString
}
USAGE
// now
var now = new Date();
var d1 = new Date("October 13, 1995 11:13:00")
var d2 = new Date("March 13, 2005 11:13:00")
// from now
alert( now.from( d1 ) )
// time elapsed between two dates
alert( now.from( d1, d2 ) )
FIDDLE
Related
I don't understand how this works. can someone explain it to me? Especially the variable name "prepand" which I've seen as "prepend" when I look it up. Also, what does the ? mean in (hour>12)?
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday","Monday","Tuesday","Wednesday
","Thursday","Friday","Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12)? " PM ":" AM ";
hour = (hour >= 12)? hour - 12: hour;
if (hour===0 && prepand===' PM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Noon';
}
else
{
hour=12;
prepand=' PM';
}
}
if (hour===0 && prepand===' AM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Midnight';
}
else
{
hour=12;
prepand=' AM';
}
}
console.log("Current Time : "+hour + prepand + " : " + minute + " : " + second);
var prepand = (hour >= 12)? " PM ":" AM ";
This translates to:
var prepand;
if (hour >= 12){
prepand = "PM";
} else {
prepand = "AM";
}
This writing is a shorthand expression called ternary. It is used to assign conditional values to variables in this case.
That is a basic code which gets the current date and tell you the day and time by manipulating the date. Check the comments corresponding to the lines.
Prepand variable is used to add the AM/PM with the time
Read here in details about Date
var today = new Date(); //Creates a JavaScript Date instance that represents a single moment in time
var day = today.getDay(); // return the index of the day
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ","Thursday","Friday ","Saturday "];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();// getHours() method returns the hour for the specified date
var minute = today.getMinutes();//getMinutes() method returns the minutes in the specified date
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour; //? is a part of ternary operator which will check if hour >=12 or not. If >= then prepand in PM otherwise AM
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " +
second);
I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>
I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));
I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function. Thank you for any help on this.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * d2Y);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays > 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
my new function only returns minutes and other and wont update to change of day
I assume you are fetching the timestamp from a mysql database. This was also answered here. The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.
you can see that your splitting was not correct...
this is working fine..
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');
splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;
splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;
you can now perform what ever you want to..
I want a js script that converts inputted time to 24 hour format or 12 hour format.
Example,
time is entered as 10_10_am result should be:-
10:10 AM (12 hr format) and 10:10 (24 hr format)
time is entered as 10_10_pm result should be:-
10:10 PM (12 hr format) and 22:10 (24 hr format)
HTML
<input type="text" id="textbox1"/>
<input type="button" id="b1" value="convert 12 hr"/>
<input type="button" id="b2" value="convert 24 hr"/>
<div id="result"></div>
JS
$(document).ready(function () {
function am_pm_to_hours(time) {
console.log(time);
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
return (sHours +':'+sMinutes);
}
function hours_am_pm(time) {
var hours = time[0] + time[1];
var min = time[2] + time[3];
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours.length < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
$('#b1').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = hours_am_pm(n1[0]+n1[1]);
$('#result').text(time);
});
$('#b2').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = am_pm_to_hours(n1[0]+':'+n1[1]+' '+n1[2]);
$('#result').text(time);
});
});
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/
updated after Adrian P 's comment
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/4
function hours_am_pm(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var min = Number(time.match(/:(\d+)/)[1]);
if (min < 10) min = "0" + min;
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
I am not sure if there is any specific function that already exists, but this is fairly easy to write.
Considering your input is always ##_##_pm or ##_##_am you can split this string on every _ and grab first value as hours, second as minutes and compare the third
and
if it's pm add 12 hours to the hours variable for 24 hr format.
You need a function that takes 2 parameters (format and string)
It will look something like this:
function timeFormat(format, str){
var timeParts=str.split("_");
if(format==12){
return timeParts[0] + ":" + timeParts[1] + " " + timeParts[2];
}else if(format == 24){
var hours = timeParts[0];
if(timeParts[2] == "pm")
hours += 12;
return hours + ":" + timeParts[1]
}
}