problems converting timestamp to new Date - javascript

I have a timestamp of:
1399043514913
Which in reality is Fri, 02 May 2014 15:11:54 GMT but I'm getting Sat, 05 Dec 46303 06:35:13 GMT
How can i correctly convert the timestamp to the Fri, 02 May date?
I'm trying:
var dateTime = new Date(milliseconds * 1000);
var UTCString = new Date(dateTime).toUTCString();
What i really want to end up with is a Date object that i can use getDate(), getMonth(), etc on so i can put the date in any format i like.
Alternatively I'd like a way of converting 1399043514913 to 02/05/2014 15:11:54
Update:
Problem solved thanks to #JensB,
Here's my millseconds to date format converter as a result:
function formatTimeStamp(milliseconds) {
if (typeof milliseconds === "string")
milliseconds = parseInt(milliseconds.match(/\d+/g)[0]);
var dateTime = new Date(milliseconds);
var dateVar = new Date(dateTime);
var ISOString = new Date(dateVar).toISOString();
var UTCString = new Date(dateVar).toUTCString();
function pad(s) { return (s < 10) ? ("0" + s) : s.toString(); }
var dateTimeParts = {
dd: pad(dateVar.getDate()),
MM: pad(dateVar.getMonth() + 1),
yyyy: dateVar.getFullYear().toString(),
yy: dateVar.getFullYear().toString().substring(2, 4),
HH: pad(dateVar.getHours()),
mm: pad(dateVar.getMinutes()),
ss: pad(dateVar.getSeconds())
};
var execute = function(string) {
for (var key in dateTimeParts)
string = string.replace(key, dateTimeParts[key]);
return string;
};
return {
ISOString: ISOString,
UTCString: UTCString,
date: execute("dd/MM/yyyy"),
time: execute("HH:mm"),
dateTime: execute("dd/MM/yy HH:mm:ss"),
dateTimeParts: dateTimeParts
};
}

just running this code (same as in your question)
var dateTime = new Date(1399043514913);
var UTCString = new Date(dateTime).toUTCString();
alert(UTCString);
Gives me
Fri, 02 May 2014 15:11:54 GMT
http://jsfiddle.net/DqSGJ/
Edit as per comment, this work?
$( document ).ready(function() {
var dateTime = new Date(1399043514913);
var dateVar = new Date(dateTime);
var UTCString = dateVar.toUTCString();
$("#dt").text(UTCString);
$("#dt2").text("Month: " + dateVar.getMonth());
$("#dt3").text("GetDate: " + dateVar.getDate());
});
Fiddler: http://jsfiddle.net/DqSGJ/3/

Related

How to convert date format into different formate

Hello I want to convert
March 2018 to 032018
in jQuery.I used
var d = new Date($('.selected_month').find("td:first").text());
But it is giving result is:
Thu Mar 01 2018 00:00:00 GMT+0530 (IST)
You need to use getMonth() and getFullYear() on returned date object to format date as per requirement. Also, you need to add 1 to returned month as getMonth method is 0 index based:
(d.getMonth()+1).toString() + d.getFullYear().toString()
Try this
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
return [month,year].join('');
}
Call this function : formatDate('March 2018') // output : 032018
Try converting the date object you end up with to a string:
Try the following snippet, just change var d = new Date() to var d = new Date($('.selected_month').find("td:first").text()).
var d = new Date();
var twoDigitMonth = (d.getUTCMonth() + 1).toString().padStart(2, "0");
var year = d.getUTCFullYear();
var result = twoDigitMonth + year;
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...or try this...
console.log(
new Date("March 2018")
.toLocaleDateString('en-EN', {month: '2-digit',year: 'numeric'})
.replace('/','')
)

Converting any kind of date format to MM\DD\YYYY

I am converting this 2 sets of date to the format MM\DD\YYYY
1.Thu Aug 31 15:00:00 GMT+08:00 2017
2017-08-09
When I'm converting the 1st one I use this code.
var STD_Date = STD_data[i][4]; //<----This is where the date comes.
var date = convertDate(STD_Date);
var datearray = date.split("/");
var New_STDDate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
This is the function convertDate()
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
This is how I format the second one.
This is the function
var toMmDdYy = function(input) {
var ptrn = /(\d{4})\-(\d{2})\-(\d{2})/;
if(!input || !input.match(ptrn)) {
return null;
}
return input.replace(ptrn, '$2/$3/$1');
};
This is how I use it.
var startdate = form.startdate //<--- comes from HTML Picker (Format "YYYY-MM-DD")
toMmDdYy(startdate)
My question is this how can I have a function that will format the date whether it is the 1st or the 2nd one?
Convert_TimeStamp_Date(){
//This is where to code will go to convert
//to MM\DD\YYYY
}
//Then call it
var startdate = "2017-08-08"
var timestamp = "Thu Aug 31 15:00:00 GMT+08:00 2017"
Convert_TimeStamp_Date(startdate);
Convert_TimeStamp_Date(timestamp);
//both of them the output must be "MM\DD\YYYY"
This is the current code but looking forward for a better one. WORKING
//Time Stamp to MM\DD\YYYY
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
var chopdate = [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
var datearray = chopdate.split("/");
var newdate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
return newdate;
}
//YYYY-MM-DD tp MM\DD\YYYY
var toMmDdYy = function(input) {
var ptrn = /(\d{4})\-(\d{2})\-(\d{2})/;
if(!input || !input.match(ptrn)) {
return null;
}
return input.replace(ptrn, '$2/$3/$1');
};
//Convert Date based on input to MM\DD\YYYY
function ConverSpedDate(input){
if( input.lenght > 10 ) return toMmDdYy(input);
return convertDate(input);
}
This should work
convertDate = function( input ){
if( input.lenght > 10 ) return convertDate( input );
return toMmDdYy( input );
}
You can test each pattern and reformat accordingly. Your reformatting functions appear to be cumbersome and error prone, consider the following:
var startdate = "2017-08-23"
var timestamp = "Thu Aug 31 15:00:00 GMT+08:00 2017"
function reformatTimestamp(s) {
if (/\d{4}-\d\d-\d\d/.test(s)) {
return reformatISOtoMDY(s);
} else if (/[a-z]{3} [a-z]{3} \d\d \d\d:\d\d:\d\d \w{3}\+\d\d:\d\d \d{4}/i.test(s)) {
return reformatCustomToMDY(s);
}
}
// Reformat YYYY-MM-DD to MM\DD\YYYY
function reformatISOtoMDY(s) {
var b = s.split(/\D/);
return b[1] + '\' + b[2] + '\' + b[0];
}
function reformatCustomToMDY(s) {
var months = '. jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
var b = s.split(/ /);
return ('0' + months.indexOf(b[1].toLowerCase())).slice(-2) +
'\' + ('0' + b[2]).slice(-2) + '\' + b[5];
}
console.log(reformatTimestamp(startdate))
console.log(reformatTimestamp(timestamp))
The format MM\DD\YYYY is unusual and likely to confuse.
As you've tagged this as a GAS question, have you looked at Utilities.formatDate()? Documentation here, but in short it takes 3 parameters: a date object, a time-zone string & a format string. The TZ & format are taken from the Java SE SimpleDateFormat class.
In your instance, try this:
var ts = "Thu Aug 31 15:00:00 GMT+08:00 2017";
var d = new Date(ts);
Logger.log(Utilities.formatDate(d, "GMT+08:00", "MM/dd/yyyy")); // logs 08/31/2017
Note that you will have to set the time-zone in the output yourself. You could extract it from the timestamp via a regex, for example. As the JS Date primitive is milliseconds 1970-01-01T00:00:00 UTC, you can set your output TZ to suit your needs.
I also +1 the recommendations to stick to ISO date & time formats: MM/dd/yyyy absent locale information is just asking for trouble.

How to convert timestamp to readable date/time?

I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed

convert date string to JSON date format

In my javascript i enter date in below format as string
12.12.2014
I want to convert to JSON date format like below
/Date(1358866800000)/
How could i achieve this. I tried below code which converts to JSON format but doesnt work.
function convertToJSONDate(strDate){
var dt = new Date(strDate);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';
}
When i try to use above function like convertToJSONDate("12.12.2014"), i get date like this '/Date(NaN)/
How could i achieve this?
The string you are passing to Date's constructor is not valid
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
var dt = new Date(splitted[2],splitted[0],splitted[1]);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';
}
convertToJSONDate("12.1.2014");
Another simplified version could be:
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
//var dt = new Date(splitted[2],splitted[0],splitted[1]);
var newDate = new Date(Date.UTC(splitted[2], splitted[0], splitted[1]));
return '/Date(' + newDate.getTime() + ')/';
}
convertToJSONDate("12.1.2014");
#AlexBcn Great answer, but you need to subtract 1 from the month because months are zero-based.
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
var newDate = new Date(Date.UTC(splitted[2], (splitted[1] - 1), splitted[0]));
return '/Date(' + newDate.getTime() + ')/';
}
//console.log(convertToJSONDate("10.01.2018"));
//Output: Wed Jan 10 2018 01:00:00 GMT+0100 (Central European Standard Time)
//Output without subtraction: Sat Feb 10 2018 01:00:00 GMT+0100 (Central European Standard Time)
try like this..
#JsonSerialize(using=CustomJsonDateSerializer.class)
#JsonDeserialize(using=CustomJsonDateDeserializer.class)

Incrementing a date in JavaScript

I need to increment a date value by one day in JavaScript.
For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.
How can I increment a date by a day?
Three options for you:
1. Using just JavaScript's Date object (no libraries):
My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:
// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:
// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());
2. Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
3. Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
Tomorrow in one line in pure JS but it's ugly !
new Date(new Date().setDate(new Date().getDate() + 1))
Here is the result :
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.
const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS
.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Two methods:
1:
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)
2: Similar to the previous method
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Via native JS, to add one day you may do following:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
Another option is to use moment library:
const date = moment().add(14, "days").toDate()
Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
Slice the date from the returned value and then increment by the number of days you want.
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):
Date.prototype.shiftDays = function(days){
days = parseInt(days, 10);
this.setDate(this.getDate() + days);
return this;
}
$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
Result:
Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200
Adding one Hour to the date, will make it work perfectly (but does not solve the problem).
$date = new Date(2014, 9, 16,0,1,1);
Result:
Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
Incrementing date's year with vanilla js:
start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020
Just in case someone wants to increment other value than the date (day)
Timezone/daylight savings aware date increment for JavaScript dates:
function nextDay(date) {
const sign = v => (v < 0 ? -1 : +1);
const result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
const offset = result.getTimezoneOffset();
return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
This a simpler method ,
and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
Use this function, it´s solved my problem:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}
Assigning the Increment of current date to other Variable
let startDate=new Date();
let endDate=new Date();
endDate.setDate(startDate.getDate() + 1)
console.log(startDate,endDate)

Categories