JS in HTML for time displays single digit minutes - javascript

Good day,
I've been using the following time function JS in an HTML code. I'm still in the progress of learning and understanding JS and been playing around with it. However, I recently noticed that whenever my minutes are less than 10, the 0 is taken away, say 14:5 instead of 14:05. Is there quick format way to fix this?
Thanks in advance, here's the JS function
function updateClock() {
var now = new Date(),
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
time = now.getHours() + ':' + now.getMinutes();
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
// document.getElementById('time').innerHTML = [date, time].join(' ');
document.getElementById('time').innerHTML = ["Today is", date, "and the time is", time].join(' ');
setTimeout(updateClock, 1000);
}
updateClock();

You should be able to check if your minutes value is less than 10 and append a 0 to the front of it :
// If the minutes are greater than 10, pad them with a '0'
time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
Example
You can see a working example here and demonstrated below :

As far as I know, there is no built-in method for this. However, you can use a ternary operator to add the 0 when necessary.
var mins = now.getMinutes();
var minsFixed = mins < 10 ? '0' : '' + mins;
time = now.getHours() + ':' + minsFixed;

Just use one more format function like this and call it everywhere:
function zero(num) {
return num < 10 ? '0' + num : num;
}

Related

JS: Formatting ISO Date String to Custom Format?

I have an ISO Date string such as "2020-08-12T03:02:47Z". I want to convert these to "August 12, 2020 3:02PM". Would I have to concert it to a timestamp and work backwards to accomplish this?
you should look at the moment.js package
npm i moment
console.log(moment(yourVariable).format('LLLL'))
https://momentjs.com/docs/
You can use formatting options of the Internationalization API. For instance like this:
let fmt = new Intl.DateTimeFormat('en-US', {
dateStyle: "long",
timeStyle: "short",
timeZone: "UTC",
hour12: true
});
// Demo
let str = fmt.format(new Date("2020-08-12T03:02:47Z"));
console.log(str); // "August 12, 2020 at 3:02 AM"
// Optional: when you don't like the "at" or the space before "AM" or "PM":
str = str.replace(/ (..)$| at\b/g, "$1");
console.log(str); // "August 12, 2020 3:02AM"
You had to build a new date and from this get the values and reformat them.
For month use an array. For the hours get AM/PM and the hours (0-12/0-11 = 0-23). For the 2-digit minutes add before a string "0" and get than the last 2 chars. For hours you could even so but you show us hours as 1-digit.
const MONTH = ['January,', 'February', 'March', 'April', 'May', 'June', 'JUly', 'August', 'September', 'October', 'November', 'December'];
let date = new Date ('2020-08-12T03:02:47Z');
let time = date.getHours();
let hours = (time<13) ? time : time % 12;
let amPm = hours >= 12 ? 'PM' : 'AM'
date = MONTH[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hours + ':' + ('0' + date.getMinutes()).slice(-2) + amPm;
console.log(date);
Ciao, try to use moment suing format 'LLL'. Like this:
let date = '2020-08-12T03:02:47Z'
console.log(moment(date).format('LLL'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Straight forward add days to current date javascript

I apologize as I'm sure this question has been answered already but there's so many different solutions from different years that my head is just spinning from viewing all the different solutions. But can someone please help with providing a straight forward javascript solution to display (x) days after current date?
All I'm trying to accomplish is having a notice on a page - "We are currently accepting bookings for March XX, 2017 or after" at the top.
OR is there anything I can to the code below to make it add (X) days as I'm using this to show current date.
var MONTH_NAME = ['January', 'Febuary', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
function showTime() {
function twoDigit(n) {
return ('0' + n).slice(-2);
}
function iso8601(date) {
return date.getFullYear() +
'-' + twoDigit(1 + date.getMonth()) +
'-' + twoDigit(date.getDate()) +
'T' + twoDigit(date.getHours()) +
':' + twoDigit(date.getMinutes());
}
function en_US(date) {
var h = date.getHours() % 12;
return MONTH_NAME[date.getMonth()] +
' ' + date.getDate() +
', ' + date.getFullYear();
}
var timeEl = document.getElementById('time');
if (timeEl !== null) {
var now = new Date();
timeEl.innerHTML = en_US(now);
timeDiv.setAttribute('datetime', iso8601(now));
}
};
setInterval(showTime, 1000);
Please and thank you.
You can use setDate and getDate methods to solve your problem. Take a look at addDays method I have written. Hope this helps.
var MONTH_NAME = ['January', 'Febuary', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
function showTime() {
function twoDigit(n) {
return ('0' + n).slice(-2);
}
function iso8601(date) {
return date.getFullYear() +
'-' + twoDigit(1 + date.getMonth()) +
'-' + twoDigit(date.getDate()) +
'T' + twoDigit(date.getHours()) +
':' + twoDigit(date.getMinutes());
}
function en_US(date) {
var h = date.getHours() % 12;
return MONTH_NAME[date.getMonth()] +
' ' + date.getDate() +
', ' + date.getFullYear();
}
function addDays(date, days){
var newDate = new Date(date.getTime());
newDate.setDate(newDate.getDate() + days);
return newDate;
}
var timeEl = document.getElementById('time');
if (timeEl !== null) {
var now = new Date();
timeEl.innerHTML = en_US(now) + ' to ' + en_US(addDays(now, 15));
timeEl.setAttribute('datetime', iso8601(now));
}
};
setInterval(showTime, 1000);
<div id="time"></div>

Show current day in the title of jquery datepicker

How can I show current full date in the title of jquery datepicker like this :
05 July 2015 because it show me just July 2015
You could use a function like this in onSelect
function showDateInTitle(picker) {
var span = picker.dpDiv[0].querySelector('.ui-datepicker-day'),
df, month;
if (span === null) {
month = picker.dpDiv[0].querySelector('.ui-datepicker-month');
if (!month) return;
span = document.createElement('span');
span.setAttribute('class', 'ui-datepicker-day');
df = document.createDocumentFragment();
df.appendChild(span);
df.appendChild(document.createTextNode('\u00a0'));
month.parentNode.insertBefore(
df,
month
);
}
span.textContent = picker.selectedDay;
}
Still looking through API for a handler for after the datepicker is shown before choice is made
You can implement an afterShow as described here with a slight modification to get the instance
$(function() {
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
$.datepicker._updateDatepicker_original(inst);
var afterShow = this._get(inst, 'afterShow');
if (afterShow)
afterShow.apply((inst.input ? inst.input[0] : null), [inst]);
}
});
Now DEMO
I couldn't find a non-hacky way of doing it, but changing the defaults config to the text you want to show might do it for you:
var defaults = {
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]
};
var today = new Date();
var month = today.getMonth();
defaults.monthNames[month] = today.getDate() + ' ' + defaults.monthNames[month];
$.datepicker.setDefaults(defaults);
Here is a working plnkr: http://plnkr.co/edit/gfp95VOchd4fhQOktIL3?p=preview
Here is my solution, it is a simple jquery solution that append the day value to the current datepicker widget.
$('#datepicker').click(function(){
var $datePickerBox = $('#ui-datepicker-div');
//var $datePickerBox = $(this).closest('.ui-datepicker.ui-widget');
var $monthName = $datePickerBox.find('.ui-datepicker-month');
var currentDay = '';
if($(this).val().trim().length==0){
currentDay = $datePickerBox.find('.ui-datepicker-today').text();
} else {
currentDay = $datePickerBox.find('.ui-datepicker-current-day').text();
}
$monthName.text( currentDay + " " + $monthName.text() );
});
Code pen link
http://codepen.io/anon/pen/WvzKJo
If you want to always show the current date at the top and not the selected date, using #PaulS.'s code change
span.textContent = picker.selectedDay;
to
span.textContent = new Date().getDate();
Demo

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Format date in javascript with time [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
How would I format a date in javascript in the format: June 2, 2013, 1:05 p.m.
Here is a relevant link, but I'm still having trouble getting this exact formatting, based on Date(). http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
Why not write a function to get bits of the date for you and return an Object which lets you build a string as easily as string concatenation of Object properties.
The example below will always base answer on UTC time
var easyDate = (function () {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
thstndrd = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
return function (d) {
var dow = d.getUTCDay(),
dom = d.getUTCDate(),
moy = d.getUTCMonth(),
y = d.getUTCFullYear(),
h = d.getUTCHours(),
m = d.getUTCMinutes(),
s = d.getUTCSeconds();
return {
dom: '' + dom,
th: thstndrd[dom % 10],
day: days[dow],
moy: '' + (moy + 1),
month: months[moy],
year: '' + y,
ampm: h < 12 ? 'a.m.' : 'p.m.',
hh: h < 10 ? '0' + h : '' + h,
sh: '' + (h % 12 || 12),
mm: m < 10 ? '0' + m : '' + m,
ss: s < 10 ? '0' + s : '' + s,
};
};
}());
var o = easyDate(new Date());
// Object {dom: "2", th: "nd", day: "Sunday", moy: "6", month: "June"…}
o.month + ' ' + o.dom + ', ' + o.sh + ':' + o.mm + ' ' + o.ampm;
// "June 2, 8:43 p.m."
This should be useful to you: http://blog.stevenlevithan.com/archives/date-time-format
i would suggest moment.js. here it is: http://momentjs.com/
import it and do this
moment().format('LLL');
this is what you want
At w3schools you can find a complete reference to Javascript's Date object
Then you can use the methods to combine into a string of your liking.
var d = new Date();
d.getHours() + ":" + ...
There isn't a method to get the month name, you will need to get the number and create a switch.
The hour is in 24h format, so you have to convert and calculate if it is am or pm.
The day and year you can get directly using getDate() and getFullYear()
References
w3schools
MDN

Categories

Resources