How to keep updating datetime every minute in Javascript? - 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

Related

Getting issue while calculating the time difference using 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.

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 Javascript clock to increment based on a button click

I have the following piece of JavaScript which currently displays a digital clock on my webpage. I am creating a web based interactive story which is based on a day in the office. Everytime the user clicks a button to proceed onto the next part of the story I want to increment the clock by 30 minutes. Currently the clock is just showing real time. Ideally it would need to start at 9:00 am for the story then increment as the user goes through.
I have absolutely no idea how to do this and am fairly new to JavaScript, hopefully someone can help!
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000); });
To start at 09:00 o'clock, you could use
var d = new Date();
d.setHours(9);
d.setMinutes(0);
d.setSeconds(0);
Then, I would recommend using moment.js
function onClick() {
d = moment(d).add(30, "minutes").toDate();
var el = document.getElementById('clock');
el.innerHTML = moment(d).format("HH:mm:ss");
}
You can also do it without moment.js
function pad(t) {
return t < 10 ? "0" + t : t;
}
function onClick() {
d.setMinutes(d.getMinutes() + 30);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = pad(h) + ":" + pad(m) + ":" + pad(s);
document.getElementById("clock").innerHTML = time;
}
JSFiddle Demo (moment.js)
JSFiddle Demo (vanilla)
Working code (jquery), but you need to modify it according to your needs,
function displayTime(currentTime, hours, minutes, seconds) {
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
$('#clock').text(hours + ":" + minutes + ":" + seconds + " " + meridiem);
}
$(function() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
$('#increment30').on('click', function() {
currentTime.setMinutes(currentTime.getMinutes() + 30);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
displayTime(currentTime, hours, minutes, seconds);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='clock'>sss</div>
<button id='increment30'>INCREMENT 30</button>
Hi here is another one try here http://jsfiddle.net/Ltq9dhaw/ :
var time = new Date();
time.setHours(9);
time.setMinutes(0);
time.setSeconds(0);
function displayTime() {
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var meridiem = "am"; // Default is AM
if (hours > 12) {
hours = hours - 12; // Convert to 12-hour format
meridiem = "PM"; // Keep track of the meridiem
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
document.querySelector('#add').addEventListener('click',function(){
var minutes = 30;
time = new Date(time.getTime() + minutes*60000);
displayTime();
});
displayTime();
I'm gonna throw my hat in the ring here too.
var date = new Date(); // create a new Date object
date.setHours(9); // set it to 09:00:00
date.setMinutes(0);
date.setSeconds(0);
setInterval(function(){ // loop...
date.setSeconds(date.getSeconds()+1); // increment the seconds by 1
var str = ''; // build up a formatted string from the Date object
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
str += h.toString().length==1 ? '0' : ''; // if we have a single digit, prepend with a '0'
str += h;
str += ':'
str += m.toString().length==1 ? '0' : ''; // and again
str += m;
str += ':'
str += s.toString().length==1 ? '0' : ''; // and again
str += s;
$('#time').html(str); // set the element with ID 'time' to contain the string we just built
}, 1000); // ... every second
$('#increment').click(function(){ // when i click the element with id 'increment'
date.setMinutes(date.getMinutes()+30); // add 30 minutes to our Date object
});
Note that you will need to include jQuery on your page.
You can do that with the following snippet:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Since you are using jQuery you can keep it simple:
function fmt2(v){return v<10?'0'+v:''+v;}
$(function(){
var t=new Date();t.setHours(9);t.setMinutes(0);t.setSeconds(0);
var offset=t.getTime() - new Date().getTime();
function displayTime(){
var currentTime= new Date((new Date()).getTime()+offset);
var hours = currentTime.getHours();
var meridiem=hours>=12?"PM":"AM";
hours=hours%12;
if (hours==0) hours=12;
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
$('#clock').text( fmt2(hours)+':'
+fmt2(minutes)+':'
+fmt2(seconds)+' '+meridiem);
}
$('#newtime').click(function(){offset+=60*30*1000;});
setInterval(displayTime,1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock">09:00:00 AM</div>
<a id="newtime" href=#>add time</a>
I am working basically with the real time but there is an offset applied to it. The offset is calculated such, that the clock will always start at 9:00 AM.

Getting 2 Local Times for User

What I'm trying to do is for example if the local time is 6:00PM I would like to display the time 10 minutes ahead which would be 6:10PM and for the other time I would like to go 50 minutes back from the current time so that would be 5:10PM.. what I have so far does neither since I can only figure out how to display the current time
<script>
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
</script>
How do I go back 50 minutes and ahead 10 minutes?
This should suffice
<script>
var futureTime = new Date();
futureTime.setMinutes(futureTime.getMinutes()+10);
var pastTime = new Date();
pastTime.setMinutes(pastTime.getMinutes()-50);
</script>
Then just use the pastTime and futureTime variables with your existing display code.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
function formatDate(d)
{
var hours = d.getHours();
var minutes = d.getMinutes();
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
{
minutes = "0" + minutes;
}
return hours + ":" + minutes + " " + suffix;
}
var currentTime = new Date();
var futureTime = new Date(currentTime.getTime());
futureTime.setMinutes(futureTime.getMinutes() + 10);
var pastTime = new Date(currentTime.getTime());
pastTime.setMinutes(pastTime.getMinutes() - 50);
document.write("<b>" + formatDate(currentTime) + "</b>");
document.write("<b>" + formatDate(futureTime) + "</b>");
document.write("<b>" + formatDate(pastTime) + "</b>");

Categories