Is it possible to increment a date object by one day without converting the object to an epoch number?
For example the traditional way will convert the date object to an epoch number:
var today = new Date();
var tomorrow = new Date(today.valueOf()); // copy date object without converting to epoch
tomorrow.setDate(tomorrow.getDate() + 1); // now gets converted to epoch :'(
The set* methods don't "convert to epoch number", they modify the date's internal time value and return the modified value. The date object is still a date.
let today = new Date();
today.setHours(0,0,0,0); // Start of day
let tvToday = +today;
let tomorrow = new Date(today);
// setDate adjusts the time value and returns it
let tvTomorrow = tomorrow.setDate(tomorrow.getDate() + 1);
console.log('Today\'s date: ' + today.toDateString());
console.log('Today\'s time value: ' + tvToday);
console.log('Tomorrow\'s date: ' + tomorrow.toDateString());
console.log('Tomorrow\'s time value: ' + tvTomorrow);
// May vary from 24 by up to 1 hour depending on crossing DST boundaries
console.log('Difference in hours: ' + ((tvTomorrow - tvToday)/3.6e6));
If you want a method that adds a day and returns a new Date object, write a function, maybe named addDays, that takes a date and number of days to add and returns a new Date object with the days added. Lots of libraries have such functions, they're not hard to write.
Not sure if you can do that without converting. Maybe convert back after.
var today = new Date();
var tomorrow = new Date(today.valueOf());
const x = tomorrow.setDate(tomorrow.getDate() + 1);
console.log(x) //epoch
const z = new Date(x)
console.log(z.toString())
Related
I'm currently populating a table with data from a soap web service, the date comes as a string (example 44250). I created a function to format it into a yyyy/mm/dd format.
Outside the loop I have this function:
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
Inside the loop I have:
else if (detailsItem == details[i].children[1].innerHTML) {
const dbDays = days[i].innerHTML;
const daysInt = parseInt(dbDays, 0);
const newDate = firstDate.addDays(daysInt);
// Format the date to a readable value
const partsDate = {
date: newDate.getDate(),
month: newDate.getMonth() + 1,
year: newDate.getYear() + 1900,
};
finalDate = `${partsDate.date}/${partsDate.month}/${partsDate.year}`;
const td = document.createElement("td");
td.textContent = finalDate;
tr.appendChild(td);
}
the else if is just checking when to add the date to the table while populating it.
I now need to send a request to the service using the date again but in the previous format, but the date has to be in the same row as the button click, the service only accepts the string format of the date, I'm currently stuck and unsure on how to format it back.
This is the button click function which has to then format the date back to a format such as 44250.
btn.onclick = function () {
// Loops through the table to find the slot and date when clicking the button on the same row
var tableRow = document.getElementById("booking-table"),
rIndex;
for (var i = 0; i < tableRow.rows.length; i++) {
tableRow.rows[i].onclick = function () {
rIndex = this.rowIndex;
bookingDay = this.cells[1].innerHTML;
bookingSlot = this.cells[2].innerHTML;
console.log(bookingSlot, bookingDay);
};
}
Any help on how to accomplish this would be appreciated.
The value "44250" looks like the number of days since 31 Dec 1899 (the epoch), which means a value of "1" converts to 1 Jan 1900. If that's correct, you can create a Date from it using:
let dbDays = '44250';
let date = new Date(1900, 0, dbDays); // 24 Feb 2021
In this algorithm, 1 is 1 Jan 1900 and 0 is 31 Dec 1899.
You can convert it back to an epoch offset using the reverse algorithm:
let dbDays = Math.round((date.getTime() - new Date(1899, 11, 31) / 8.64e7);
Which gets the difference in ms since the date and the epoch, then divides by ms in one day and rounds it to account for possible daylight saving effects where days aren't exactly 24 hours long. This method only works for whole days, it doesn't work for partial days.
The algorithm might be out by a day if 1 Jan 1900 should be 0 rather than 1, just adjust the base dates used in the functions.
Simple functions to go from dbDate to Date instance and back are:
// Convert epoch days to Date
function toDate(dbDays) {
return new Date(1900, 0, +dbDays);
}
// Convert Date to epoch days
function toDBDays(date) {
return Math.round((date - new Date(1899,11,31)) / 8.64e7);
}
// Format date as dd/mm/yyyy
function formatDate(d) {
let z = n => ('0'+n).slice(-2);
return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear();
}
// Parse date in d/m/y format, any non-digit separator
function parseDate(s) {
let [d,m,y] = s.split(/\D/);
return new Date(y, m - 1, d)
}
// Example
let dbDays = '44250';
let d1 = toDate(dbDays); // 24 Feb 2021
let ts = formatDate(d1); // 24/02/2021
let d2 = parseDate(ts); // date object
console.log(dbDays + ' to Date: ' + ts);
console.log(ts + ' to dbDays: ' + toDBDays(d2));
PS Given the epoch won't change, instead of creating a date for 31 Dec 1899 and getting its time value, the constant -2209111200000 can be used.
Notes on your code:
const daysInt = parseInt(dbDays, 0);
The second argument to parseInt is a radix or base to use for conversion to number. The value 0 is replaced with 10 (the default radix), so the above is equivalent to:
const daysInt = parseInt(dbDays, 10);
Then there is:
const partsDate = {
date: newDate.getDate(),
month: newDate.getMonth() + 1,
year: newDate.getYear() + 1900,
};
The getYear method returns a 2 digit year, it's not recommended and is supported mostly for historic reasons, use getFullYear instead.
Using an object for temporary storage is not really optimal, just use variables:
let date = newDate.getDate(),
month = newDate.getMonth() + 1,
year = newDate.getFullYear();
Note that this doesn't pad single digit days or months with leading zeros so will produce timestamps like 1/1/2021 instead of 01/01/2021.
You can use momentjs to convert the date easier: https://momentjs.com/ ,
about the use of the date after you pass that value to the html, can you store that value on some global variable,sesion or localstorage? and then use it later? to call again the soap service? i'm asumming your working on a web page, cause your using html :)
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000
I simply need the number of seconds from the midnight of the present day.
It's a labyrinth of JS Date methods I can't untangle from.
I already searched for an off-the-shelf snippet. I tried this but it returns local time, not UTC:
let date = new Date(),
d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(),
date.getUTCSeconds())),
e = new Date(d),
secsSinceMidnight = Math.floor((e - d.setUTCHours(0,0,0,0)) / 1000);
I think you had the right idea, but got lost in the implementation. Your assignment to d is just a very long winded way of creating a copy of date that is equivalent to the assignment to e.
To get "seconds from UTC midnight", create a Date for now and subtract it from a copy that has the UTC hours set to 00:00:00.000.
function secsSinceUTCMidnight() {
var d = new Date();
var c = new Date(+d);
return (d - c.setUTCHours(0,0,0,0)) / 1000;
}
console.log('Seconds since UTC midnight: ' +
secsSinceUTCMidnight().toLocaleString() + '\n' + new Date().toISOString());
I have an object containing time. For example x.time = 10:20:00.
I want to take the current time minus my objects time.
This is my code so far, but i get the error message ="Invalid Date":
for(var i = 0; i<x.length; i++){
nowDate = new Date();
minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + x[i].time);
text +- "It is "+ minutesLeft[i] + " milliseconds left";
}
In order to convert your time property into a date object you can do:
var timepieces = x.time.split(':');
var date = new Date();
date.setHours(timepieces[0]);
date.setMinutes(timepieces[1]);
date.setSeconds(timepieces[2]);
Then you can directly compare the two dates by using the getTime() method of the Date object.
nowDate.getTime() === date.getTime()
nowDate.getTime() > date.getTime()
nowDate.getTime() < date.getTime()
You can also get the difference of two dates in milliseconds:
var milliseconds = nowDate.getTime() - date.getTime();
There are a bunch of problems with your code. I'll go through and hopefully catch everything.
Use var to declare your variables inside your loop. (further reading)
When you create the variable minutesLeft you are doing a bit of weird concatenation. You told us that x.time is a string such as "10:20:00" but you are (string) concatenating that with Date.prototype.getDate which returns a number in the range 1-31 (representing the day of the month). You are essentially doing this:
minutesLeft = new Date(2017,0,1910:20:00);
Which I hope you see will not create a new date. You perhaps wanted something along the lines of
minutesLeft = new Date(2017,0,19, 10, 20, 0);
Which should give you what you want (todays date set to the appropriate time defined by x.time.
text +- does not make any sense. I suspect a typo, you meant text += which will append the value on the right to the variable text. Or, perhaps text = which will assign the value, replacing what was there
"It is "+ minutesLeft[i] + " milliseconds left" using minutesLeft[i] will take a single character from a string (or an item from an array, if the value is an array). Yours is just a date object, and is not an array, so I suspect you just meant to leave off the [i] part altogether.
If you're trying to get the difference between the current date/time and your selected date/time you need to do some arithmetic with nowDate and minutesLeft. I'm assuming this is a difference you're after.
var x = [{time:"10:20:20"}];
var text = "";
for(var i = 0; i<x.length; i++){
var nowDate = new Date();
var timeSplit = x[i].time.split(":");
var minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate());
minutesLeft.setHours(timeSplit[0]);
minutesLeft.setMinutes(timeSplit[1]);
minutesLeft.setSeconds(timeSplit[2]);
text += "It is "+ (nowDate-minutesLeft) + " milliseconds left";
}
console.log(text);
For example x.time = 10:20:00. I want to take the current time minus my objects time.
Your code seems quite confused, it seems you're trying to do the following:
var time = '10:20:00';
var timeParts = time.split(':');
var now = new Date();
// Current date and time
console.log(now.toString());
// Subtract the hours part of the time from the hours part of the current time
now.setHours(now.getHours() - timeParts[0]);
// Subtract the minutes part of the time from the minutes part of the current time
now.setMinutes(now.getMinutes() - timeParts[1]);
// Subtract the seconds part of the time from the seconds part of the current time
now.setSeconds(now.getSeconds() - timeParts[2]);
// Adjusted date and time
console.log(now.toString());
// You can set the time parts all in one go:
var now2 = new Date();
now2.setHours(now2.getHours() - timeParts[0],
now2.getMinutes() - timeParts[1],
now2.getSeconds() - timeParts[2]);
console.log(now2.toString());
Lastly, copying a date is as simple as:
var date1 = new Date();
var date2 = new Date(date1);
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000