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>
Related
I want to use the following script to refresh the time every second. Works fine, but I want it to output the format like this:
October 06 - 13:38:04.
How do you do that?
var timestamp = '<?=time();?>';
function updateTime(){
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="time"></p>
Try this:
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
Read more about it here.
Simple function for formating your date.
function dateToString(/* add timestamp parameter if you want */) {
var d = new Date(/* timestamp parameter here */);
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'October',
'November',
'December',
]
var month = months[d.getMonth() - 1];
var date = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate();
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds();
var time = (hours < 10 ? "0" + hours : hours) + ':' + (minutes < 10 ? "0" +
minutes : minutes) + ':' + (seconds < 10 ? "0" + seconds : seconds);
return month + ' ' + date + ' - ' + time;
}
dateToString(/* pass timestamp argument here */);
Afaik PHP's time function return a unix timestamp and you're looking for an ES5 solution. This might help you.
const datetime = 1601984483;
var padStart = function(str, length) {
while (str.toString().length < length)
str = "0" + str;
return str;
}
var format = function (timestamp) {
var date = new Date();
var d = {
M: date.toLocaleString('default', { month: 'long' }),
d: padStart(date.getDate(), 2),
h: padStart(date.getHours(), 2),
m: padStart(date.getMinutes(), 2),
s: padStart(date.getSeconds(), 2)
};
return [[d.M, d.d].join(' '), [d.h, d.m, d.s].join(':')].join(' ');
}
console.log(format(datetime));
I want to convert date from this format "yyyy-MM-dd'T'HH:mm:ss.SSS"
to Mon, May 09 2016 08:12:29 using JavaScript, below code is not working. pls advice
var str2 = "2016-05-09T08:12:29.110";
var date2 = Date.parse( str2 );
alert( date2.toString( 'EEE, MMM d yyyy HH:mm:ss' ) );`
Try this:
var str2 = "2016-05-09T08:12:29.110";
var date2 = new Date(Date.parse(str2));
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
function pad(n, number) {
var str = number.toString();
var result = '';
for (var i=0; i<n-str.length; ++i) {
result += '0';
}
return result + str;
}
document.body.innerHTML = days[date2.getDay()] + ', ' + months[date2.getMonth()] + ' ' + pad(2, date2.getDate()) + ' ' + date2.getFullYear() + ' ' + pad(2, date2.getUTCHours()) + ':' + pad(2, date2.getMinutes()) + ':' + pad(2, date2.getSeconds());
Try this
var str2 = "2016-05-09T08:12:29.110";
var date2 =new Date(str2);
alert( date2 );
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;
}
For a project I need a very simple calendar. So I got some code from the internet and modified it.
My current Code and what I did you can see on http://jsfiddle.net/baa2tqdo/1/. To summarize here the important parts of the code.
My HTML Code:
<html>
<!-- ... -->
<div id="container">
<div class="box">
<!-- Calendar -->
<div class="calendar"></div>
</div>
</div>
<!-- ... -->
</html>
And my JavaScript Code
var calendar = function () {
var date = new Date();
createCalendarHead(date);
createCalendar(date);
// month back
$('.back').click(function () {
date = decreaseMonth(date);
$('.calendar-body').empty();
createCalendar(date);
});
// year back
$('.back-year').click(function () {
date.setYear(date.getYear() - 1);
$('.calendar-body').empty();
createCalendar(date);
});
// month forward
$('.forward').click(function () {
date = increaseMonth(date);
$('.calendar-body').empty();
createCalendar(date);
});
// year forward
$('.forward-year').click(function () {
date.setYear(date.getYear() + 1);
$('.calendar-body').empty();
createCalendar(date);
});
// Current
$('.current').click(function () {
date = new Date();
$('.calendar-body').empty();
createCalendar(date);
});
};
function increaseMonth(d) {
if (d.getMonth() == 11) {
d.setMonth(0);
d.setYear(d.getYear() + 1);
} else {
d.setMonth(d.getMonth() + 1);
}
return d;
}
function decreaseMonth(d) {
if (d.getMonth() == 0) {
d.setMonth(11);
d.setYear(d.getYear() - 1);
} else {
d.setMonth(d.getMonth() - 1);
}
return d;
}
function getLastMonth(d) {
if (d.getMonth() == 0) {
return 11
} else {
return d.getMonth() - 1;
}
}
function replaceAll(find, replace, str) {
var tempStr = str.replace(find, replace);
if (tempStr.contains(find)) {
return replaceAll(find, replace, tempStr);
}
return tempStr;
}
function createCalendarHead(d) {
var months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
var days = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
// add head and body for calendar
$('.calendar')
.append('<div class="calendar-nav">')
.append('<div class="calendar-head">')
.append('<div class="calendar-body">');
$('.calendar-nav')
.append('<div class="back-forward">')
.append('<div class="current-date">' + months[d.getMonth()] + ' ' + (d.getYear() <= 200 ? d.getYear() + 1900 : d.getYear()) + '</div>');
$('.back-forward')
.append('<input type="button" class="button back-year" value="<<"/>')
.append('<input type="button" class="button back" value="<"/>')
.append('<input type="button" class="button current" value="today"/>')
.append('<input type="button" class="button forward" value=">"/>')
.append('<input type="button" class="button forward-year" value=">>"/>');
// fill head with days
for (var c = 0; c < days.length; c++) {
$('.calendar-head')
.append('<div class="days">' + days[c] + '</div>');
}
}
function createCalendar(date) {
var months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
var days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var d = date;
var day = d.getDate();
var month = d.getMonth();
var year = d.getYear();
year <= 200 ? year += 1900 : year;
// leap year?
year % 4 == 0 && year != 1900 ? days_in_month[1] = 29 : days_in_month;
// days in current month
var total = days_in_month[month];
// calculate days of last month
var DatumMonat = d;
DatumMonat.setDate(1);
var ErsterTag = DatumMonat.getDay();
// add days of last month
for (var i = 1; i < ErsterTag; i++) {
$('.calendar-body').append('<div class="day-box last-month">' +
(days_in_month[getLastMonth(d)] - ((ErsterTag - 1) - i)) +
'</div>');
}
var $tagDatum;
var $classTagDatum;
for (i = 1; i <= total; i++) {
// create current date as string
$tagDatum = (i < 10 ? '0' + i : i) + '' + (month + 1) + '' + year;
$classTagDatum = "." + $tagDatum;
$('.calendar-body ').append('<div class="day-box ' + $tagDatum + '">');
if (day == i) $($classTagDatum).append('<div class="tag today">' + i + '</div>');
else $($classTagDatum).append('<div class="tag">' + i + '</div>')
}
$('.current-date')
.empty()
.text(months[month] + ' ' + (year <= 200 ? year + 1900 : year));
}
But the days of the last month are not displayed correctly (except for the current month) and I can not find my mistake. My second problem is to display the month and year correctly. After changing the year two times it does not work anymore. I hope someone can help me to solve my problems or at least give me some tips. Thank you in advance.
Don't use magic numbers like 0, 30, 11. It will complicate the code.
Pass selected date of calendar to your function
Set date to 1 to the passed variable (set month to 1 for previous year)
Add day -1 to new date.
Set passed date to new date.
Use same approach for next month or year selection. Use date functions to change the date rather than setting numbers of month ir year. This will handle leap year and different month days
Use date.getFullYear(). getYear() is deprecated.
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