Setting a set date with javascript - javascript

Using a countdown plugin but I think I'm setting the date and time wrong.
Code:
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(2016,10,27, 10,00,00);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true
});
});
I'm attempting this:
var futureDate = new Date(2016,10,27, 10,00,00);
Which is 27th October 2016 at 10am
Coding up 52 days though so I must be doing something wrong

Which is 27th October 2016 at 10am
That's where you're going wrong. Months in JavaScript are 0-indexed (January is 0, December is 11), the 10th month is actually November.
var futureDate = new Date(2016,9,27,10,00,00);

Related

How to Set a Countdown with time zone?

How to Set a Countdown with time zone via countdown.js?
(https://www.npmjs.com/package/countdown)
I need:
begin at noon Eastern Standard Time on Wednesday November 22, 2017
today is 2017.11(Nov).01
and I used this code for checking tommorrow
const countdown = require('countdown');
var aaa = countdown( new Date(2017, 11, 2) ).toString();
console.log(aaa)
But my Output is:
1 month, 19 hours, 21 minutes and 11 seconds
That Output is incorrect maybe because I'm in uae Now
You can utilize moment timezone to get the time zone with countdown.js: https://momentjs.com/timezone/
Kind of like:
var tz = moment.tz.guess(),
date = moment.tz('2017-11-22', tz),
now = new Date(),
diff = (date.valueOf() / 1000) - (now.getTime() / 1000)

flipclock countdown to specific date in specific timezone without reset

I am trying to create countdown to a specific date using flipclock without the timer resetting or people in different time-zones seeing different numbers. For example, I want to countdown to Feb 20, 12:00am MST.
My problem is that the clock resets when the browser is refreshed after it reaches 0, the time shows negative numbers. If people viewing this clock with the current configuration, it is counting down to Feb 20, 12am in their timezone.
I've started with the countdown to New Years compiled clock and set my date, but not sure how else to address the timezone and reset issues.
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
var clock;
$(document).ready(function() {
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false,
callbacks: {
stop: function() {
$('.message').html('The clock has stopped!');
}
}
});
});
Part solving timezone issue (a bit ugly):
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
currentDate.setHours(currentDate.getHours() - 7);
Part limiting time difference to not less than zero:
// Limit time difference to zero
if (diff < 0) {
diff = 0;
}
Since the time you'd like to count down to is a specific time in a specific time zone, then the easiest way is to pre-convert that time to UTC, and count down to that instead.
On Feb 20th 2016, US Mountain Time is at UTC-7, therefore:
2016-02-20 00:00:00 MST == 2016-02-20 07:00:00 UTC
So,
var currentDate = new Date();
var futureDate = Date.UTC(currentDate.getUTCFullYear(), 1, 20, 7, 0, 0);
var diff = (futureDate - currentDate.getTime()) / 1000;
I'll let someone else answer WRT the specifics of FlipClock and your reset issue - though you might consider asking it in a separate question. (Try to ask only one question at a time in the future.)

Set the timezone of a Date object

I'm currently trying to develop a countdown timer page. Here is the countdown timer code:
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date("July 01, 2015 22:00:00");
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
if(diff < 0){
// Instantiate a countdown FlipClock
clock = $('.clock').FlipClock(0, {
clockFace: 'DailyCounter',
countdown: true
});
$('.message').html('Lets Go!!');
$('.Go').removeAttr("disabled");
$( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
}
else{
// Instantiate a countdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
callbacks: {
stop: function() {
$('.message').html('Lets Go!!');
$('.Go').removeAttr("disabled");
$( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
}
}
});
}
});
The problem is that the countdown time varies per timezone. For example, a user in Australia will have a three-hour-shorter countdown time than that of a user from Malaysia (GMT+8).
How can I standardize/set the initial countdown date's timezone to GMT+8 so that users in different timezones have the same countdown time?
Based on our discussion, this example code works to convert any timezone time into UTC+8 timezone time.
var d = new Date();
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000 /* convert to UTC */ + (/* UTC+8 */ 8) * 60 * 60 * 1000);
console.log('UTC+8 Time:', d);
Here is a JSFiddle for reference.
Although the console output shows that the timezones of the date objects are not UTC+0800, their date values (year, month, date, etc...) have all been converted into UTC+0800 time.
It is just not possible to edit the actual timezone of date objects, but it is possible to edit their date values to reflect the new timezone, and that is what we are doing here.
GMT time is the same as UTC time.
Use JavaScript setUTCDate() Method
Example
Set the day of the month, according to UTC:
var d = new Date();
d.setUTCDate(15);
The result of d will be:
Wed Jul 15 2015 10:47:28 GMT+0400 (Russian Standard Time)

How can I add 1 day to current date?

I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

Using answers from prompt for a calculation

Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp

Categories

Resources