Getting issue while calculating the time difference using JavaScript - javascript

I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new 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;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}

Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new 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;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.

Related

Date.ISOString wrongly converts from timestamp? [duplicate]

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)

Add 5 minutes to current time javascript

I am getting the current date as below:
var now = new Date();
I want to add 5 minutes to the existing time. The time is in 12 hour format. If the time is 3:46 AM, then I want to get 3:51 AM.
function DateFormat(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
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 = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
// var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function OnlyTime(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
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 = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function convertTime(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;
alert(sHours + ":" + sMinutes);
}
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function convertTime(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;
alert(sHours + ":" + sMinutes);
}
// calling way
var now = new Date();
now = DateFormat(now);
var next = addMinutes(now, 5);
next = OnlyTime(next);
var nowtime = convertTime(next);
How to add 5 minutes to the "now" variable?
Thanks
You should use getTime() method.
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
function DateFormat(date){
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth()+1);
var hours = date.getHours();
var minutes = date.getMinutes();
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = days + '/' + month + '/' + year + '/ '+hours + ':' + minutes;
return strTime;
}
var now = new Date();
console.log(DateFormat(now));
var next = AddMinutesToDate(now,5);
console.log(DateFormat(next));
//Date objects really covers milliseconds since 1970, with a lot of methods
//The most direct way to add 5 minutes to a Date object on creation is to add (minutes_you_want * 60 seconds * 1000 milliseconds)
var now = new Date(Date.now() + (5 * 60 * 1000));
console.log(now, new Date());
get minutes and add 5 to it and set minutes
var s = new Date();
console.log(s)
s.setMinutes(s.getMinutes()+5);
console.log(s)
Quite easy with JS, but to add a slight bit of variety to the answers, here's a way to do it with moment.js, which is a popular library for handling dates/times:
https://jsfiddle.net/ovqqsdh1/
var now = moment();
var future = now.add(5, 'minutes');
console.log(future.format("YYYY-MM-DD hh:mm"))
Try this:
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (5 * 60 * 1000));
I'll give a very short answer on how to add any string of the form ny:nw:nd:nh:nm:ns where n is a number to the Date object:
/**
* Adds any date string to a Date object.
* The date string can be in any format like 'ny:nw:nd:nh:nm:ns' where 'n' are
* numbers and 'y' is for 'year', etc. or, you can have 'Y' or 'Year' or
* 'YEar' etc.
* The string's delimiter can be anything you like.
*
* #param Date date The Date object
* #param string t The date string to add
* #param string delim The delimiter used inside the date string
*/
function addDate (date, t, delim) {
var delim = (delim)? delim : ':',
x = 0,
z = 0,
arr = t.split(delim);
for(var i = 0; i < arr.length; i++) {
z = parseInt(arr[i], 10);
if (z != NaN) {
var y = /^\d+?y/i.test(arr[i])? 31556926: 0; //years
var w = /^\d+?w/i.test(arr[i])? 604800: 0; //weeks
var d = /^\d+?d/i.test(arr[i])? 86400: 0; //days
var h = /^\d+?h/i.test(arr[i])? 3600: 0; //hours
var m = /^\d+?m/i.test(arr[i])? 60: 0; //minutes
var s = /^\d+?s/i.test(arr[i])? 1: 0; //seconds
x += z * (y + w + d + h + m + s);
}
}
date.setSeconds(date.getSeconds() + x);
}
Test it:
var x = new Date();
console.log(x); //before
console.log('adds 1h:6m:20s');
addDate(x, '1h:6m:20s');
console.log(x); //after
console.log('adds 13m/30s');
addDate(x, '13m/30s', '/');
console.log(x); //after
Have fun!
This function will accept ISO format and also receives minutes as parameter.
function addSomeMinutesToTime(startTime: string | Date, minutestoAdd: number): string {
const dateObj = new Date(startTime);
const newDateInNumber = dateObj.setMinutes(dateObj.getMinutes() + minutestoAdd);
const processedTime = new Date(newDateInNumber).toISOString();
console.log(processedTime)
return processedTime;
}
addSomeMinutesToTime(("2019-08-06T10:28:10.687Z"), 5)
Add minutes into js time by prototype
Date.prototype.AddMinutes = function ( minutes ) {
minutes = minutes ? minutes : 0;
this.setMinutes( this.getMinutes() + minutes );
return this;
}
let now = new Date( );
console.log(now);
now.AddMinutes( 5 );
console.log(now);

jquery new date() 12 hour format [duplicate]

How do you display a JavaScript datetime object in the 12 hour format (AM/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;
}
console.log(formatAMPM(new Date));
If you just want to show the hours then..
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);
Output : 7 AM
If you wish to show the minutes as well then...
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);
Output : 7:23 AM
Here's a way using regex:
console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
This creates 3 matching groups:
([\d]+:[\d]{2}) - Hour:Minute
(:[\d]{2}) - Seconds
(.*) - the space and period (Period is the official name for AM/PM)
Then it displays the 1st and 3rd groups.
WARNING: toLocaleTimeString() may behave differently based on region / location.
If you don't need to print the am/pm, I found the following nice and concise:
var now = new Date();
var hours = now.getHours() % 12 || 12; // 12h instead of 24h, with 12 instead of 0.
This is based off #bbrame's answer.
As far as I know, the best way to achieve that without extensions and complex coding is like this:
date.toLocaleString([], { hour12: true});
Javascript AM/PM Format
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date and time as a string.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="fullDateTime()">Try it2</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var d = new Date();
var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
document.getElementById("demo").innerHTML = n;
}
function fullDateTime() {
var d = new Date();
var n = d.toLocaleString([], { hour12: true});
document.getElementById("demo2").innerHTML = n;
}
</script>
</body>
</html>
I found this checking this question out.
How do I use .toLocaleTimeString() without displaying seconds?
In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:
let now = new Date();
new Intl.DateTimeFormat('default',
{
hour12: true,
hour: 'numeric',
minute: 'numeric'
}).format(now);
// 6:30 AM
Using default will honor browser's default locale if you add more options, yet will still output 12hr format.
Use Moment.js for this
Use below codes in JavaScript when using moment.js
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
The format() method returns the date in specific format.
moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)
My suggestion is use moment js for date and time operation.
https://momentjs.com/docs/#/displaying/format/
console.log(moment().format('hh:mm a'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Updated for more compression
const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
hours %= 12;
hours = hours || 12;
minutes = minutes < 10 ? `0${minutes}` : minutes;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
};
console.log(formatAMPM(new Date()));
use dateObj.toLocaleString([locales[, options]])
Option 1 - Using locales
var date = new Date();
console.log(date.toLocaleString('en-US'));
Option 2 - Using options
var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));
Note: supported on all browsers but safari atm
Short RegExp for en-US:
var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"
Please find the solution below
var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;
It will return the following format like
09:56 AM
appending zero in start for the hours as well if it is less than 10
Here it is using ES6 syntax
const getTimeAMPMFormat = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0' + hours : hours;
// appending zero in the start if hours less than 10
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM
I fount it's here it working fine.
var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
var d = new Date();
var hour = d.getHours(); /* Returns the hour (from 0-23) */
var minutes = d.getMinutes(); /* Returns the minutes (from 0-59) */
var result = hour;
var ext = '';
if(date_format == '12'){
if(hour > 12){
ext = 'PM';
hour = (hour - 12);
result = hour;
if(hour < 10){
result = "0" + hour;
}else if(hour == 12){
hour = "00";
ext = 'AM';
}
}
else if(hour < 12){
result = ((hour < 10) ? "0" + hour : hour);
ext = 'AM';
}else if(hour == 12){
ext = 'PM';
}
}
if(minutes < 10){
minutes = "0" + minutes;
}
result = result + ":" + minutes + ' ' + ext;
console.log(result);
and plunker example here
Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString
It's a really handy library, especially if you are planning on doing other things with date objects.
<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth = todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12;
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>
Hopefully this answer is a little more readable than the other answers (especially for new comers).
Here's the solution I've implemented in some of my sites for informing the last time the site code was modified. It implements AM/PM time through the options parameter of date.toLocaleDateString (see related Mozilla documentation).
// Last time page code was updated/changed
const options = {
year: "numeric",
month: "long",
weekday: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: true // This is the line of code we care about here
/*
false: displays 24hs format for time
true: displays 12, AM and PM format
*/
};
let last = document.lastModified;
let date = new Date(last);
let local = date.toLocaleDateString("en-US", options);
let fullDate = `${local}`;
document.getElementById("updated").textContent = fullDate;
Which output is in the format:
Saturday, May 28, 2022, 8:38:50 PM
This output is then displayed in the following HTML code:
<p>Last update: <span id="updated">_update_date_goes_here</span></p>
NOTE: In this use case, document.lastModified has some weird behaviors depending if it's run locally or on a external server (see this Stack Overflow question). Though it works correctly when I run it in my GitHub page (you should see it in action in the site at the footer).
Here is another way that is simple, and very effective:
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(11);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');
document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());
</script></div><!-- #time -->
you can determine am or pm with this simple code
var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';
try this
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? "pm" : "am";
function formatTime( d = new Date(), ampm = true )
{
var hour = d.getHours();
if ( ampm )
{
var a = ( hour >= 12 ) ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
}
var hour = checkDigit(hour);
var minute = checkDigit(d.getMinutes());
var second = checkDigit(d.getSeconds());
// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}
function checkDigit(t)
{
return ( t < 10 ) ? `0${t}` : t;
}
document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
<p>ampm true: <span id="time1"></span> (default)</p>
<p>ampm false: <span id="time2"></span></p>
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
var meridian = h >= 12 ? "PM" : "AM";
h = h % 12;
h = h ? h : 12;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
var strTime = h + ":" + m + ":" + s + " " + meridian;
document.getElementById('time').innerText = strTime;
setTimeout(startTime, 1000);
}
startTime();
<h1 id='time'></h1>
If you have time as string like so var myTime = "15:30",
then you can use the following code to get am pm.
var hour = parseInt(myTime.split(":")[0]) % 12;
var timeInAmPm = (hour == 0 ? "12": hour ) + ":" + myTime.split(":")[1] + " " + (parseInt(parseInt(myTime.split(":")[0]) / 12) < 1 ? "am" : "pm");
var d = new Date();
var hours = d.getHours() % 12;
hours = hours ? hours : 12;
var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " +
("00" + d.getDate()).slice(-2) + " " +
d.getFullYear() + " " +
("00" + hours).slice(-2) + ":" +
("00" + d.getMinutes()).slice(-2) + ":" +
("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM');
document.getElementById("demo").innerHTML = test;
<p id="demo" ></p>
<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>
<script>
var AM_or_PM = "AM";
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = twelve_hour_time(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('clock_display').innerHTML =
h + ":" + m + ":" + s +" "+AM_or_PM;
var t = setTimeout(startTime, 1000);
}
function checkTime(i){
if(i < 10){
i = "0" + i;// add zero in front of numbers < 10
}
return i;
}
// CONVERT TO 12 HOUR TIME. SET AM OR PM
function twelve_hour_time(h){
if(h > 12){
h = h - 12;
AM_or_PM = " PM";
}
return h;
}
startTime();
</script>
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
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;
var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
return dateTime;
}
Here my solution
function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
strampm= "PM";
} else {
strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}
function checkTimeAddZero(i) {
if (i < 10) {
i = "0" + i
}
return i;
}
const formatAMPM = (date) => {
try {
let time = date.split(" ");
let hours = time[4].split(":")[0];
let minutes = time[4].split(":")[1];
hours = hours || 12;
const ampm = hours >= 12 ? " PM" : " AM";
minutes = minutes < 10 ? `${minutes}` : minutes;
hours %= 12;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
} catch (e) {
return "";
}
};
const startTime = "2021-12-07T17:00:00.073Z"
formatAMPM(new Date(startTime).toUTCString())
This is the easiest Way you can Achieve this using ternary operator or you can also use if else instead !
const d = new Date();
let hrs = d.getHours();
let m = d.getMinutes();
// Condition to add zero before minute
let min = m < 10 ? `0${m}` : m;
const currTime = hrs >= 12 ? `${hrs - 12}:${min} pm` : `${hrs}:${min} am`;
console.log(currTime);
Or just simply do the following code:
<script>
time = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt_clock').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function(){time()}, 0);
}
time2 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
if (h>12) {
document.getElementById('txt_clock_stan').innerHTML = h-12 + ":" + m + ":" + s;
}
var t = setTimeout(function(){time2()}, 0);
}
time3 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (h>12) {
document.getElementById('hour_line').style.width = h-12 + 'em';
}
document.getElementById('minute_line').style.width = m + 'em';
document.getElementById('second_line').style.width = s + 'em';
var t = setTimeout(function(){time3()}, 0);
}
checkTime = function(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>

How to get AM or PM?

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>

How to keep updating datetime every minute in Javascript?

I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc

Categories