I have a date and time that I format. It works most of the time, but if the time has a "0" in the second last space it will return wrong. For example, time "10.30" will be formatted correctly, but "10.03" will return "10.3" without the zero.
My code:
const today: Date = new Date();
const date: Date = new Date(item.receivedDateTime);
let time: string;
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = date.getHours() + ":" + date.getMinutes();
} else {
time = date.getDate() + "/" + (date.getMonth() + 1);
}
Above will format time incorrectly. What is wrong in the code? I prefer not to use padstart as it is not supported in IE11 or moment.js.
You can save the value of date.getMinutes() in a variable and check if it's smaller than 10, and if so, append a 0.
const minutes = date.getMinutes();
const formattedMinutes = (minutes < 10) ? '0' + minutes : minutes;
Finally, use the formatted value for output:
time = date.getHours() + ":" + formattedMinutes;
You can use a simple pad function
const pad = num => ("0"+num).slice(-2);
const item = {"receivedDateTime":1570000000000}
const today = new Date();
const date = new Date(item.receivedDateTime);
let time = "";
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = pad(date.getHours()) + ":" + pad(date.getMinutes());
} else {
time = pad(date.getDate()) + "/" + pad(date.getMonth() + 1);
}
console.log(time)
Instead of,
time = date.getHours() + ":" + date.getMinutes();
You can use,
var minutes = d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes();
time = date.getHours() + ":" + minutes
Related
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 have a datetime value gotten from an SQLServer database table:
2016-08-16T17:00:00Z
Using javascript, I want to format the date as follow:
16/08/2016 17:00:00
I have used the code below:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}
The result from the sample resource is:
17/71/2016
I want your help to get the output result as: "16/08/2016 17:00:00"
If all you want to do is format it then you don't need to create an actual date object, you can do a simple string replace using a regex to grab the individual parts, as per this simple demo:
var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));
In the context of your function:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
} else {
return value;
}
}
Another solution:
var parsed = Date.parse("2016-08-16T17:00:00Z"),
date = new Date(parsed),
day = date.getUTCDate(),
month = date.getUTCMonth() + 1,
year = date.getUTCFullYear(),
hour = date.getUTCHours(),
minute = date.getUTCMinutes(),
second = date.getUTCSeconds(),
dateStr = "";
day = day < 10 ? "0" + day : day;
month = month < 10 ? "0" + month : month;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
dateStr = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second;
console.log(dateStr);
Updated: The old code may change across countries, because they have different local date/time format, so I have updated to format it explicitly.
Try this
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' +seconds ;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
You can use this library to format the date as you desire with implementing some logic.
http://momentjs.com/
Just work with the function parameter value and use moment.
Example:
const date = moment("2016-08-16T17:00:00Z").date();
const month = moment("2016-08-16T17:00:00Z").month();
const hour = moment("2016-08-16T17:00:00Z").hour();
const year = moment("2016-08-16T17:00:00Z").year();
const minute = moment("2016-08-16T17:00:00Z").minute();
const sec = moment("2016-08-16T17:00:00Z").second();
// implementing some logic
console.log('' + date + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + sec);
here is the fiddle:
https://jsfiddle.net/Refatrafi/6m4m7mp3/
This is a simple one I think.
Why do I get 2015-11-04 when I run the following code in JSFiddle (new Date(1451606399999), but when I run the same code in my browser console I get 2015-12-31 (which is the value I'm expecting).
I would have thought any in either case the timezone would be the same as the code is running on the client, and why would timezone make more than a month difference in the date?
function test()
{
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("myDiv").innerHTML = formattedTime;
}
JSFiddle with code
Confusingly, date.getMonth() is 0 based, meaning 0 is January, so it should be month = date.getMonth()+1. Also confusingly date.getDay() actually returns the day of the week (0 is Sunday, 1 is Monday... etc). The function you're looking for is date.getDate()
function test(){
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(date);
document.getElementById("myDiv").innerHTML = formattedTime;
}
I want to add minutes to a date and display it.I am using the following code
function dt(){
var d = new Date();
d.setMinutes(d.getMinutes()+15*60);
var theDate = d.getFullYear() + '-' + ( d.getMonth() + 1 ) + '-' + d.getDate()+' '+d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
//var d1 = new Date( Date.parse( theDate ) + s1*60*1000 );
var d1=new Date(theDate);
var hours = d1.getHours();
var minutes = d1.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 + ' ';
var t=( d1.getMonth() + 1 )+ '/' + d1.getDate() + '/' + d1.getFullYear() +' '+strTime; alert(t+ampm);
}
dt();
This code is working fine in Chrome.But in IE and safari, it was returning NAN:NAN:NAN 12:NAN AM.
Anyone please help.
Regards
Rekha
The line:
d.setMinutes(d.getMinutes()+15*60);
will add 15 hours to the date. Why not:
d.setHours(d.getHours()+15);
Then you copy a date by creating a string then parsing it:
var theDate = d.getFullYear() + '-' + ... + d.getSeconds();
var d1 = new Date(theDate);
Do not do that. Ever. Parsing date strings is unreliable (as you've discovered) and not recommended. To copy a date, use:
var d1 = new Date(+d);
Try replacing:
var d1 = new Date(theDate);
with:
var d1 = new Date(d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
Using the Date contructor with a date string has some limitations
Timestamp:
1395660658
Code:
//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
var d = new Date(timestamp);
timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();
return timeStampCon;
};
This converts the time stamp properly in terms of time format, but the date is always:
17/0/1970
Why - cheers?
You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :
var d = new Date(timestamp*1000);
Reference
function convertTimestamp(timestamp) {
var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0.
dd = ('0' + d.getDate()).slice(-2), // Add leading 0.
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2), // Add leading 0.
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
// ie: 2014-03-24, 3:00 PM
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
return time;
}
You can get the value by calling like convertTimestamp('1395660658')
Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.
//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));
const timeStamp = 1611214867768;
const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)