Date to epoch and vice versa - JavaScript - javascript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link

You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);

var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

Related

How do I get the next day's date in JS in YYYY-MM-DD format?

Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.
Basically, if I have a date like the following:
2018-04-06
I want to be able to get the next day's date as such:
2018-04-07
I found the following snippet on SO for doing this (kind of):
var date = new Date('2018-04-06');
date.setDate(date + 1);
The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.
I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.
Strings in the format YYYY-MM-DD are parsed as UTC so in this case, do everything in UTC (see Why does Date.parse give incorrect results? and How can I add 1 day to current date?).
The toISOString method will return the string in the required format, just trim the redundant time part, e.g.
let s = '2018-04-06';
let d = new Date(s);
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().substr(0,10));
Did you try with the UTC date?
var date = new Date('2018-04-06');
console.log(date.toUTCString());
date.setDate(date.getDate() + 1);
console.log(date.toUTCString());
As it was suggested by #chrisbyte, have your tried to use toUTCString method instead of toString() method ?
As a reminder , toString is the default used when you display the date object withim the console for example
I think the "problem" you're assuming is just an incomplete understanding how Date.toString() method behaves: this method seems to to return string representing a Date object but seems to use timezone as mentionned here (on the comment in 1st example)
Here my snippet to understand more:
const originalDate = new Date('2018-04-06');
// retrieving the original timestamp
const originalTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`original date (timezone dependent): ${originalDate.toString()}`)
console.log(`original date (timezone independent): ${originalDate.toUTCString()}`)
// we add one more day
originalDate.setDate(originalDate.getDate() +1)
const dayAfterTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`updated date (timezone dependent): ${originalDate.toString()}`)
console.log(`updated date (timezone independent): ${originalDate.toUTCString()}`)
// check the differences (in milliseconds)
console.log(`difference: ${(dayAfterTimestamp-originalTimestamp)}`)
// displaying the original format (timezone independent)
At last if you want to return the date string as a YYYY-MM-DD format you may have to implement it yourself :-/ , or use toLocaleFormat method but it isn't standardized.
The logic would be to add 24 hours in milliseconds to the current time. As an example:
var myDate = new Date();
var oneMoreDay = new Date();
oneMoreDay.setTime(myDate.getTime() + 86400000);
console.log(myDate.getDate());
console.log(oneMoreDay.getDate());
An additional day has been added to the oneMoreDay variable. In your specific example you just wanted to add one more day to the ORIGINAL variable, so i'd do something such as:
date.setTime(date.getTime() + 86400000);

Get "Day" From This Formatted Timestamp In Javascript

I'm working with Javascript within Google Sheets, and I'm having trouble converting or parsing a formatted timestamp, to ultimately extract the day as a numerical value.
My code:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
Logger.log(date.getDay());
The output:
[19-06-10 17:40:56:107 BST] NaN
My goal is to extract the day number, for example, "18" from that timestamp.
However, it doesn't seem to convert it. I suspect my timestamp isn't in the correct format for the date() function, so it's about creating a function to parse it.
Hopefully, you can help me with that! :) Thank you so much.
The date object has a method like this for getting the day of the month as a number (1-31).
date.getDate();
18 is date.
var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
console.log(date.getDate());
JavaScript's Date constructor supports ISO 8601 date strings. Without using any libraries, you can do something like this:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
+ 'T' + shopifyTimestamp.slice(11, 19)
+ shopifyTimestamp.slice(20);
var date = new Date(isoDate);
console.log(date.getDate()); // 18
Also note that you're looking for date.getDate(), rather than date.getDay(). The latter returns the numerical date of the week.

Convert UTC date format into javascript format

How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN
You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...
Then you can create a new string like you need it.
possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want
The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

JavaScript date objects UK dates

I have the following code
datePicker.change(function(){
dateSet = datePicker.val();
dateMinimum = dateChange();
dateSetD = new Date(dateSet);
dateMinimumD = new Date(dateMinimum);
if(dateSetD<dateMinimumD){
datePicker.val(dateMinimum);
alert('You can not amend down due dates');
}
})
dateSet = "01/07/2010"
dateMinimum = "23/7/2010"
Both are UK format. When the date objects are compared dateSetD should be less than dateMinimumD but it is not. I think it is to do with the facts I am using UK dates dd/mm/yyyy. What would I need to change to get this working?
The JavaScript Date constructor doesn't parse strings in that form (whether in UK or U.S. format). See the spec for details, but you can construct the dates part by part:
new Date(year, month, day);
MomentJS might be useful for dealing with dates flexibly. (This answer previously linked to this lib, but it's not been maintained in a long time.)
This is how I ended up doing it:
var lastRunDateString ='05/04/2012'; \\5th april 2012
var lastRunDate = new Date(lastRunDateString.split('/')[2], lastRunDateString.split('/')[1] - 1, lastRunDateString.split('/')[0]);
Note the month indexing is from 0-11.
var dateString ='23/06/2015';
var splitDate = dateString.split('/');
var month = splitDate[1] - 1; //Javascript months are 0-11
var date = new Date(splitDate[2], month, splitDate[0]);
Split the date into day, month, year parts using dateSet.split('/')
Pass these parts in the right order to the Date constructor.
Yes, there is problem with the date format you are using. If you are not setting a date format the default date that is used is 'mm/dd/yy. So you should set your preferred date formate when you create it as following when you create the date picker:
$(".selector" ).datepicker({ dateFormat: 'dd/mm/yyyy' });
or you can set it later as:
$.datepicker.formatDate('dd/mm/yyyy');
When you try to create a date object:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:
dateSetD = new Date(dateSet.year, dateSet.month, dateSet.day);
Note: JavaScript Date object's month starts with 00, so you need to adjust your dateset accordingly.

Categories

Resources