How to Add 12 Hours to Current Date? - javascript

How to add 12 hours to the current display date? I want to have a promotional offer on my website, this promotional offer will close 12 hours from the current time.
People from different countries with different time slots will visit this, So it has to suffice to their time slot. How can I achieve this?
<html>
<font size="+1.5"><p id="date"></p></font>
<script>
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>
</html>

You can use setTime(), like this example:
n = new Date();
n.setTime(n.getTime() + (12 * 60 * 60 * 1000));
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
h = n.getHours();
mi = n.getMinutes();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y + " " + h + ":" + mi;
<html>
<font size="+1.5"><p id="date"></p></font>
</html>

Try this
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Just call addHourse function on new Date() and pass number of hours you want to add. For example
alert(new Date().addHours(12));
Okay. here is the full code.
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
}
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return month + '/' + day + '/' + year;
}
var date = getFormattedDate(new Date().addHours(12));
var date2 = new Date().addHours(12);
document.getElementById("date").innerHTML = date;
document.getElementById("date2").innerHTML = date2;
<html>
<font size="+1.5">
<p id="date"></p>
</font>
<font size="+1.5">
<p id="date2"></p>
</font>
</html>
This will print the formatted date and date in the default format. You can go with whatever you like.

Related

i want to display AM / PM using javascript [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
i try to disply time with the showing AM / PM format but i am unable to find any code can you please guide me
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.getElementById("dt").innerHTML = time;
<p id='dt'></p>
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds()+" ";
time+= dt.getHours()>=12?"PM":"AM"
document.getElementById("dt").innerHTML = time;
<div id="dt"></div>
Just check if the value less than 12, and keep the hours under 12 and return 12 instead of 0 by: (hours %12 || 12):
var dt = new Date();
var time = (dt.getHours()%12||12) + ":" + dt.getMinutes() + ":" + dt.getSeconds() + " " + (dt.getHours() < 12)===0?"AM" : "PM";
document.getElementById("dt").innerHTML = time;
Just compare the hours to if its less than 12 and if so set a variable to either AM or PM. Note that the following has the leading 0 added to the mins and secs if required (the slice will only include the 0 if the length of the value is 1).
var dt = new Date();
var hrs = dt.getHours();
var hours = hrs % 12;
var mins = '0' + dt.getMinutes();
var minutes = mins.slice(-2);
var secs = '0' + dt.getSeconds();
var seconds = secs.slice(-2);
var amPm = hrs< 12 ? 'AM' : 'PM';
var time = hours + ":" + minutes + ":" + seconds + ' ' + amPm;
document.getElementById("dt").innerHTML = time;
<p id = "dt"></p>

Why this code got an Uncaught TypeError

I want to get next day and format it into "yyyy-MM-dd HH:mm" format, but when I run this in chrome's console, I got an Uncaught TypeError: date.getHours is not a function, why? The nextDay variable is clearly an instance of Date.
But when I removed hour and minute, just kept year, month and date, it successed, can anyone tell me the reason?
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
date = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));
Your function takes a parameter named "date" and then tries to declare a local variable named "date". That declaration will be ignored, and the initializer will just overwrite the value of the parameter.
Change the name of the parameter:
function format(d) {
var year = d.getFullYear(),
month = d.getMonth(),
date = d.getDate(),
hour = d.getHours(),
minute = d.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
You are using the same variable name as the parameter, date is used twice, change the variable name like down below.
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
theDate = date.getDate(), //change the variable name
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));

Time elapsed between dates

I need to know the percentage remaining between two dates.
I've used this code:
$(function () {
var end = $('#data').text();
var formattedDate = new Date();
var day = formattedDate.getDate();
var month = formattedDate.getMonth();
month += 1;
var year = formattedDate.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var today = day + "/" + month + "/" + year;
remaining = Math.round(((end - today) * 100) / today));
alert(remaining);
});
But it does'nt work.
Any suggestion?
Thanks
You're subtracting two strings, which is why it won't work.
Subtract two Date objects instead, and you'll get the milliseconds between them (ignoring the maths as to what you define as a % of 2 dates).
var now = new Date();
var then = new Date($('#data').text());
var remaining = Math.round(((then - now) * 100) / now);
You can still, of course, get your formatted string of DD/MM/YY via;
var formattedDays = (now.getDay() < 10 ? "0" : "") + now.getDay();
var formattedMonth = (now.getMonth() < 9 ? "0" : "") + (now.getMonth() + 1);
var formattedDate = formattedDays + "/" + formattedMonth + "/" + now.getFullYear();
Note that you have an extra closing parenthesis at the end of your Math.round() line as well.

Clock and date javascript

Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone could give me tip or idea how to fix it, I would greatly appreciate it.
function timedate()
{
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var dn="PM"
var d = currentTime.getDate(); <--
var day = (d < 10) ? '0' + d : d;
var m = currentTime.getMonth() + 1; <--
var month = (m < 10) ? '0' + m : m;
var yy = currentTime.getYear(); <--
var year = (yy < 1000) ? yy + 1900 : yy;
if (hours<12)
{
dn="AM"
}
if (hours>12)
{
hours=hours-12
}
if (hours==0)
{
hours=12
}
if (minutes<=9)
{
minutes="0"+minutes
}
var clocklocation = document.getElementById('timedate');
clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
setTimeout("timedate()", 1000);
}
timedate();
Your code works, it is just not visible because you do not have seconds showing
Also change
setTimeout("timedate()", 1000);
to
setTimeout(timedate, 1000);
because it is not recommended
and remove the <--
Make sure it runs onload or after the tag you want to show it in
Alternatively remove the line and change
timedate();
to
setInterval(timedate,1000)
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date();
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yy = currentTime.getFullYear();
let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12;
hours = pad(hours);
document.getElementById('timedate').innerHTML = "" +
hours + ":" +
minutes + ":" +
seconds + dn + " " +
day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
setInterval(timedate, 1000);
});
<span id="timedate"></span>
If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works1.
1 I took the liberty of adding seconds to your code as well, to make it obvious that the clock updates. Of course, you also need to remove <-- from your code.

javascript date + 7 days

What's wrong with this script?
When I set my clock to say 29/04/2011 it adds 36/4/2011 in the week input! but the correct date should be 6/5/2011
var d = new Date();
var curr_date = d.getDate();
var tomo_date = d.getDate()+1;
var seven_date = d.getDate()+7;
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
var tomorrowsDate =(tomo_date + "/" + curr_month + "/" + curr_year);
var weekDate =(seven_date + "/" + curr_month + "/" + curr_year);
{
jQuery("input[id*='tomorrow']").val(tomorrowsDate);
jQuery("input[id*='week']").val(weekDate);
}
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.
Without declaration
To return timestamp
new Date().setDate(new Date().getDate() + 7)
To return date
new Date(new Date().setDate(new Date().getDate() + 7))
Something like this?
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
convert to date again:
date = new Date(res);
alert(date)
or alternatively:
date = new Date(res);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds;
alert(formattedTime)
In One line:
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
$('#txtEndDate').val(output);
var future = new Date(); // get today date
future.setDate(future.getDate() + 7); // add 7 days
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();
console.log(finalDate);
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Two problems here:
seven_date is a number, not a date. 29 + 7 = 36
getMonth returns a zero based index of the month. So adding one just gets you the current month number.

Categories

Resources