I want to show the time in a readable format. So I am using the below js code. But the output is different in Chrome and IE. How do I change the code to give the same output across all the browsers ?
The output in IE : 12:46 am
In Chrome : 6:16 am
Time zone is : UTC +05:30
var unReadableDate = "2016-01-25T00:46:00";
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
Can you please try replacing this
var unReadableDate = "2012-06-25T00:46:00.000Z"
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
Converting a UTC format string to a date using Javascript Date constructor is not reliable. If you want to tackle timezone issues with date you should use moment.js. To understand more you can use below link.
Javascript Date issue
OR simple way to resolve the issue is pass individual arguments in the date instead of complete string. To understand more you can use below link
DateTime UTC
Your problem is that your date string being treated as a local time vs it being treated as UTC.
Just make it unambiguous by specifying the time zone. Change
var unReadableDate = "2016-01-25T00:46:00";
to
var unReadableDate = "2016-01-25T00:46:00Z";
Related
I am using new Date() to create a customize time, and also I'm using a function to format time in am/pm:
const formatTimeAMPM = (date, midnight = { am: "AM", pm: "PM" }) => {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
hours = hours < 10 ? "0" + hours : hours;
var strTime = hours + ":" + minutes + " " + ampm;
return strTime;
};
let startDate = new Date(Date.now());
console.log('before change :',formatTimeAMPM(startDate));
startDate.setHours(8, 30, 0, 0);
console.log('after change :',formatTimeAMPM(startDate));
If you run the snippet, you will see console logs the 8:30 pm , Can anyone tell me how to set am for it when I change hour the startDate ?
Your am/pm check is backwards:
var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;
If the hour is >= 12, it should be PM not AM, so it should be:
var ampm = hours >= 12 ? ` ${midnight.pm}` : ` ${midnight.am}`;
Now if you run it, it will show 8:30 AM and if you set the hour to 20 it will show 8:30 PM
This will fix your current issue but it would be better to use an existing library for date formatting since it can get complicated, especially with i18n. There a couple popular ones such as date-fns and moment.js that will do the heavy lifting for you.
I see that I various times like
01:45
//and
15:00
I assume that date is HH:MM in military ?
While have I seen some advanced functions then parse sentences and even some using the seconds like HH:MM:SS , I am wanting a simple and accurate way of getting the HH:MM
So I assume 15:00 is 3:00 ?
This function below is not going to work because I already have ":"
so below assumed HHMM right? when I believe I need HH:MM to be parsed ?
var getTravelTimeFormatted = function (str) {
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
Update
Ok, I assume that 15:00 is 3:00 , right?
So i stripped out the incoming ":" and then add it back
problem is the result is 25.0 so what does that mean?
var getTravelTimeFormatted = function (str) {
str = str.replace(/:/g,'');
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
console.log(getTravelTimeFormatted('15:00'));
Given a string HH:MM you can just split then subtract 12 hours. Here's a naive solution that doesn't check for invalid input.
function TwelveHourFormat(time) {
var dtParts = time.split(":");
var hours = dtParts[0];
var minutes = dtParts[1];
var suffix = "AM";
if (hours > 12) {
hours = hours - 12;
suffix = "PM";
}
else if (hours == "00") {
hours = 12;
suffix = "AM";
}
else if (hours == "12") {
suffix = "PM";
}
return (hours + ":" + minutes + " " + suffix);
}
This is a duplicate of Converting 24 hour time to 12 hour time w/ AM & PM using Javascript. Jasen's answer is fine, and more concise than the duplicate, but the function can be a little more concise:
/* Convert time in 24 hour hh:mm format to 12 hour h:mm ap format
** #param {string} time - in hh:mm format (e.g. 14:30)
** #returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function to12HourTime(time) {
var b = time.split(/\D/);
return (b[0]%12 || 12) + ':' + b[1] +
(b[0]<11? ' AM' : ' PM');
}
// Some tests
['23:15','2:15','03:15','00:30'].forEach(function(v) {
console.log(v + ' => ' + to12HourTime(v));
});
I am trying to compare dates in javascript.
I have a hardcoded date (03/23/2015 11:20 am) in of , and I am trying to compare it with the current date in the same format.
But I am always getting it as not same.
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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 date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var timeNow = formatDate(D);
var startTime6 = document.getElementById('tno6_time').innerHTML;
if (timenow == startTime6) {
alert("Same");
}
else {
alert("not same");
}
Your's javascript portion :
var d = new Date();
var timeNow = formatDate(D);
if (timenow == startTime6) {
alert("Same");
}
Here check in above code you are creating variable with name d and you are passing variable D which is not declared.Here you have also typo in timeNow not timenow.It should be like
var timeNow = formatDate(d);
if (timeNow == startTime6) {
alert("Same");
}
Apart from that check both the variables value either with console.log() function or with alert() and see if there are same then It should alert the 'Same' else 'not same'.
And keep in mind new Date() will always give you current time so if you are comparing with hard coded date then Only once there are the possibility that result should come 'Same' and It will only occur when you are executing this code when the hard coded date and time exactly the same.
It is very hard to check your code in that way because millisecond change will affect your result.
Check this demo
I have the following code
INPUT:
var dateString = "10/30/2014 02:15 PM +00:00";
var a = dateString .split(/[^0-9]/);
var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);
var minutes=dateVal.setMinutes(dateVal.getMinutes() + 330);
var hours = dateVal.getHours();
if(parseInt(hours,10) < 10){
hours = "0"+hours;
}
var minutes = parseInt(dateVal.getMinutes());
var ampm = parseInt(hours, 10) >= 12 ? 'PM' : 'AM';
hours = parseInt(hours % 12);
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
strTime = hours + ':' + minutes + ' ' + ampm;
return strTime
OUTPUT:
Actual: 7:45 AM
Expected : 7:45 PM
I am able to get the time zone converted but not able to get the desired output as i like to get 7:45 PM but i always get the way opposite.
Can some help me out with this.
The problem is, that a time past midday doesn't get detected, when you convert the string. Try to search for PM and if found increase your hours by twelve:
var dateString = "10/30/2014 02:15 PM +00:00";
var a = dateString .split(/[^0-9]/);
if(dateString.indexOf("PM") != -1) a[3] = Number(a[3]) + 12;
var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);
Hi Everyone I am sorry if this question has been answered before but I haven't been able to find a solution. I am completely new to js so please be nice :)
I wanted to ask how can I have the time display inside a div? I can't get this function to display on my page. When I launch the page in the browser, it is just blank.
Thank you, I hope my question makes sense.
document.getElementById("para1").innerHTML = formatAMPM(date);
function formatAMPM(date) {
var elem = document.getElementById("para1");
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
You need this:
document.getElementById("para1").innerHTML = formatAMPM(new Date());
And you might also want to wrap it in something like jQuery's ready() to make sure the DOM has been loaded:
$(document).ready(function() {
// Handler for .ready() called.
});
http://api.jquery.com/ready/
jQuery's isn't the only way, but just a suggestion.
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours || 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
DEMO VIEW
You can return it in a user-familiar time string with toLocaleTimeString().
A replace will remove the seconds counter-
function formatAMPM() {
var d=new Date().toLocaleTimeString();
return d.replace(/^(\d{2}:\d{2}):\d{2}(.*)/, '$1$2');
}
Or you can call this or your method on a timer-
onload= function(){
window.showTimer= setInterval(function(){
var date= new Date(),
hours= date.getHours(),
time= date.getMinutes();
if(time<10) time= '0'+time;
document.getElementById("para1").innerHTML=
(hours%12 || 12)+':'+time+(hours>= 12? ' pm':' am');
},1000);
}