Is There a way to use Document.getTime() From a Certain Time? - javascript

By default document.getTime() returns the number of milliseconds since January 1st, 1970, but if I want it from a different date do I have to use addition/subtraction to do so, or can I just pass some sort of parameter that accomplishes the same thing?

If you wanted a time from lets say December 25 2013
var date = new Date("December 25, 2013 00:00:00");
document.write( dt.getTime() );

You can't do that without subtraction, but this works:
var d=new Date("November 25, 2014 02:01:00");
var n=new Date("November 25, 2014 02:00:00");
var x = d.getTime() - n.getTime();
document.write(x + " milliseconds since "+n);
Please note, document.write shouldn't be used in production
If you want a time from now to anytime in the past, this will do it:
var d=new Date();
var n=new Date("November 25, 2014 02:00:00");
var x = d.getTime() - n.getTime();
document.write(x + " milliseconds since "+n);

Related

Javascript New Date() / UTC - GMT cross browser

The issue:
Different formats for new Date() in IE 10 - IE 11.
Javascript:
IE 11 / Chrome :
var m = new Date("2014-07-04T04:00:00");
console.log(m); // Fri Jul 04 2014 06:00:00 GMT+0200 (W. Europe Summer Time)
IE 10:
var m = new Date("2014-07-04T04:00:00");
console.log(m); // Fri Jul 4 04:00:00 UTC+0200 2014
Is possible to use one ring to rule them all?
You shouldn't pass a string to new Date, specifically for this reason.
Instead, you should either give it the individual arguments:
new Date(2014, 6, 4, 4, 0, 0); // remember months are zero-based
Or, if you want to give it a time in UTC, try:
var d = new Date();
d.setUTCFullYear(2014);
d.setUTCMonth(6);
d.setUTCDate(4);
d.setUTCHours(4);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
You can, of course, make a function to do this.
Alternatively, if you have a timestamp, you can simply do:
var d = new Date();
d.setTime(1404446400000);
To complete the answer a bit. The UTC example given is dangerous, given that you execute on 31st of May (or any other 31st day of month) the following:
var d = new Date();
d.setUTCFullYear(2014);
d.setUTCMonth(5);
d.setUTCDate(4);
d.setUTCHours(4);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
it will produce "2014 July 4 04:00:00".
So prefer Date.UTC function instead:
new Date(Date.UTC(2014, 5, 4, 4, 0, 0, 0))
it will produce "2014 June 4 04:00:00".

What's wrong on adding Days at this Date function?

This is my code:
var dat = new Date("24/03/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
but it print Tue Jan 06 2015 00:00:00 GMT+0100?
The date is wrong: should be 31/03/2013 (and I'd like to print it in this format).
My browser (Chrome) prints "Invalid date", but apparently yours interprets the initializing date in mm/dd/yyyy format instead of dd/mm/yyyy. Therefore it thinks it's the 3rd day of the 24th month of 2013, which is January 3rd, 2015.
I'm not sure why it would print it as January 6th if you add 7 days to it.
The safest way is to give the numbers explicitly:
var dat = new Date( 2013, 2, 24 );
Change the format of your date to put the day after the month:
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
For me this returns:
Sun Mar 31 2013 00:00:00 GMT+0000 (GMT Standard Time)
You should have to give the month number first. Then you'll get the correct answer
Try this code
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
var curr_date = dat.getDate();
var curr_month = dat.getMonth() + 1; //Months are zero based
var curr_year = dat.getFullYear();
console.log(curr_date + "/" + curr_month + "/" + curr_year);
You should print out your date before you add seven. I suspect it's being set to the 3rd day of the 24th month in 2013, which equates to somewhere close to January 2015.
That's why you're getting a date well advanced from the current one. Why it's giving you the 6th of January rather than the 10th, I'm not sure, but you can probably fix it just by changing your input string to the US format of mm/dd/yyyy, or using a more explicit constructor that's not subject to misinterpretation:
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
try this!!!
var aDate = new Date(2013,3,24);
aDate.setDate(aDate.getDate() + 7);
var dateString = aDate.getDate() + "-" + aDate.getMonth() + "-" + aDate.getFullYear();
alert(dateString);

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');

Javascript how to convert sstring to date

I need to write a script to update a time. I want to make it increase by 20 seconds so
"Jun 23, 2011 12:00 AM"
becomes
"Jun 23, 2011 12:20 AM"
How can I do that?
The easiest way to manipulate dates is with the Date.js library available at http://datejs.com/. Then it would be:
var d = Date.parse("Jun 23, 2011 12:00 AM").add(20).seconds();
Or if d is already set to a date, you could simply do:
var d = new Date(d.getTime() + 20000);
var seconds = 1000; // 1 second = 1000 milliseconds
var originalDate = Date.parse("Jun 23, 2011 12:00 AM");
var newDate = new Date(originalDate + 2 * seconds);

Dates before Jan. 01 1970?

I'm trying to write a javascript function that calculates the time since Oct 11th, 1910 so I can throw it into a timer for a project I'm working on. I get that javascript's milliseconds works from epoc, but I don't and can't find a way to get the milliseconds since a date earlier than 01.01.1970
Does anyone have any loose code that can do the above that they may be willing to share?
var oldGoodTimes = new Date(1910, 9, 11); // January = 0
var actualDate = new Date();
console.log(actualDate.getTime() - oldGoodTimes.getTime());
Try this:
var yeOldeTimes = new Date();
yeOldeTimes.setFullYear(1910, 9, 11);
var myNewDate = new Date();
console.log("Milliseconds since Ye Olde Times: " + (myNewDate - yeOldeTimes));
Number of milliseconds since Oct 11th, 1910
console.log(new Date() - new Date('1910', '10', '11'))
// new Date().valueOf() - milliseconds since 1970
// -(new Date('1910', '10', '11')).valueOf() - milliseconds from 1910 since 1970

Categories

Resources