This is my code:
var data = "1387568966 ";
var parsedDate = new Date(Date.parse(data));
but if I print parsedDate it says "Invalid Date".
Where am I wrong? It should works with timestamp.
To create a date with a timestamp use the Date constructor taking a number as argument (the number of milliseconds since Epoch) :
var data = "1387568966 ";
var parsedDate = new Date(data*1000); // converts from "seconds" to milliseconds
or
var parsedDate = new Date(parseFloat(data)*1000);
if you want to make your code more obvious.
You are using Data.parse() wrong, it does the opposite of what you think.
From MDN:
The Date.parse() method parses a string representation of a date, and
returns the number of milliseconds since January 1, 1970, 00:00:00
UTC.
Instead, just parse your string into an integer and pass it to the date constructor.
Related
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.
I am trying to pick up value from datetimepicker tetxbox and compare those values with current time.
JSFiddle
//startTime textbox text = 19/12/2014 03:58 PM
var startTime = Date.parse($('[id$=txtStartDate]').val().toString());
//endTime textbox text = 19/12/2014 04:58 PM
var endTime = Date.parse($('[id$=txtEndDate]').val().toString());
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
if (currentTime >= startTime && currentTime <= endTime) {
alert();
}
Date.parse() is used fro converting string to milliseconds since Jan 1 1970.
Date.now() returns current date milliseconds since Jan 1 1970.
But the above conversion methods are not working properly.
What should be logic to compare datetime by first sonverting string in format like 19/12/2014 03:58 PM to Date object and then do comparing.
The problem is Date() expects date format mm/dd/yyyy, so your date is invalid.
You can fix your date like this:
function toValidDate(datestring){
return datestring.replace(/(\d{2})(\/)(\d{2})/, "$3$2$1");
}
var startTime = Date.parse(toValidDate($('[id$=txtStartDate]').val().toString()));
var endTime = Date.parse(toValidDate($('[id$=txtEndDate]').val().toString()));
var currentTime = Date.now();
alert(startTime);
alert(endTime);
alert(currentTime);
DEMO: http://jsfiddle.net/3mztdaja/3/
Since that format isn't documented as being supported by Date.parse, your best bet is to parse it yourself, which isn't difficult: Use String#split or a regular expression with capture groups to split it into the individual parts, use parseInt to convert the parts that are numeric strings into numbers (or, with controlled input like this, just use the unary + on them), and then use new Date(...) to use those numbers to create a Date instance.
One gotcha: The month value that new Date expects is zero-based, e.g. 0 = January. Also remember to add 12 to the hours value if the input uses AM/PM instead of the 24-hour clock.
Or, of course, use any of several date/time handling libraries, such as MomentJS.
You should use this method
var startTime = new Date(year, month, day, hours, minutes, seconds, milliseconds);
this a demo http://jsfiddle.net/hswp7x8k/
to extrat value from string you can use this method
dd = '19/12/2014 03:58';
dd.match(/(\d+)\/(\d+)\/(\d+)\s*(\d+):(\d+)/);
this a demo http://jsfiddle.net/w3wow1ay/2/
I am running into a problem with when I try to pass a Date() variable I have created to a function that I working on, if I put the following in the function I have passed the variable to this is what I see.
console.log("quickScreenCompletedDate: " + typeof quickScreenCompletedDate);
console.log("quickScreenCompletedDate: " + quickScreenCompletedDate);
here is the output
"quickScreenCompletedDate: number"
"quickScreenCompletedDate: 1403409600000"
However when I create the variable I am creating it as a Date() class
var completedDate = Date.parse('#Model.CompletedDate');
then I call the function like this.
previousDenialDate_ChangeHandler(isChild, completedDate);
for completeness here is the function definition
function checkIfShouldShowPreviouslyDeniedMessage(isChild, quickScreenCompletedDate) {
The problem is that i need to do some logic on the compeletedDate var and that works just fine as you can see I am getting the number 1403409600000, now though, I also need to display this to the user and when I try to call toDateString() that fails as it isn't a date object anymore. What am I missing that is causing this.
Thanks
From the documentation for Date.parse()
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
So:
var completedDate = Date.parse('2014-07-01');
returns 1404172800000 (of type number)
Instead, do:
var completedDate = new Date('#Model.CompletedDate');
which will give you an actual Date object instance.
Javascript stores dates as milliseconds since Jan 1 1970.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You do the math in milliseconds and then convert to a date using toDateString() to print it as a date OR you can create a new Date and pass in the milliseconds to the constructor.
Example
new Date(1403409600000);
why don't you try with new Date?
new Date(year, month, day [, hour, minute, second, millisecond ])
in your case try
var completedDate = new Date('#Model.CompletedDate.Year','#Model.CompletedDate.Month','#Model.CompletedDate.Day');
or
var completedDate = new Date('#YourModelVariable');
If you use Date.parse Beware of timezone issues
var d = Date.parse("10/22/2014");
refer here for documentation of Date.parse
I was trying to convert date object into long format (may be in milliseconds format) as we do in java.
So to fulfill my need, after some trial and error, I found below way which works for me:
var date = new Date();
var longFormat = date*1; // dont know what it does internally
console.log(longFormat); // output was 1380625095292
To verify, I reverse it using new Date(longFormat); and it gave me correct output. In short I was able to fulfill my need some how, but I am still blank what multiplication does internally ? When I tried to multiply current date with digit 2, it gave me some date of year 2057 !! does anyone know, what exactly happening ?
The long format displays the number of ticks after 01.01.1970, so for now its about 43 years.
* operator forces argument to be cast to number, I suppose, Date object has such casting probably with getTime().
You double the number of milliseconds - you get 43 more years, hence the 2057 (or so) year.
What you are getting when you multiply, is ticks
Visit: How to convert JavaScript date object into ticks
Also, when you * 2 it, you get the double value of ticks, so the date is of future
var date = new Date()
var ticks = date.getTime()
ref: Javascript Date Ticks
getTime returns the number of milliseconds since January 1, 1970. So when you * 1 it, you might have got value of this milliseconds. When you * 2 it, those milliseconds are doubled, and you get date of 2057!!
Dates are internally stored as a timestamp, which is a long-object (more info on timestamps). This is why you can create Dates with new Date(long). If you try to multiply a Date with an integer, this is what happens:
var date = new Date();
var longFormat = date*1;
// date*1 => date.getTime() * 1
console.log(longFormat); // output is 1380.....
Javascript tries to find the easiest conversion from date to a format that can be multiplied with the factor 1, which is in this case the internal long format
Just use a date object methods.
Read the docs: JavaScript Date object
var miliseconds=yourDateObject.getMiliseconds();
If You want to get ticks:
var ticks = ((yourDateObject.getTime() * 10000) + 621355968000000000);
or
var ticks = someDate.getTime();
Javascript date objects are based on a UTC time value that is milliseconds since 1 January 1970. It just so happens that Java uses the same epoch but the time value is seconds.
To get the time value, the getTime method can be used, or a mathematic operation can be applied to the date object, e.g.
var d = new Date();
alert(d.getTime()); // shows time value
alert(+d); // shows time value
The Date constructor also accepts a time value as an argument to create a date object, so to copy a date object you can do:
var d2 = new Date(+d);
If you do:
var d3 = new Date(2 * d);
you are effectively creating a date that is (very roughly):
1970 + (2013 - 1970) * 2 = 2056
You could try the parsing functionality of the Date constructor, whose result you then can stringify:
>
new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200"
// or something
But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY format correctly. If you had used MM/DD/YYYY, it probably would be recognized everywhere.
Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor:
var parts = "04/06/13".split("/"),
date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200
I'm trying to convert from epoch time (numeric) to a string date. I have these two values, from October of last year to March of this year: 1349064000000,1362114000000. But when I do Date(num), I get today's date returned for both.
You must use new Date(num).
Date(), without "new", doesn't create a new Date object, it only returns the current date as a string, regardless of any arguments you pass.
Try something like this:-
var date = new Date(1349064000000);
It will alert your wanted date.
var utcSeconds = 1349064000;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
alert(d);