i am getting stucked to convert date from ms (receiving from json)
i was recieving the date in json in format below
/Date(1355250600000)/
so that i converted it into ms --->
var d = response.ContributionsDate.replace("/", "").replace("/", "").replace("Date(", "").replace(")", "");
so now its d = 1355250600000
to convert i tried the code below--->
var date = new Date(d);
alert(date);
but did not work (invalid date), if anyone have any idea about date parsing, help me
d is a string, not a number.
Try
var date = new Date(+d);
instead.
The prefix + causes coercion to a number.
Incidentally, you can simplify your replace operations to
var d = +response.ContributionsDate.match(/^\/Date\((\d+)\)\/$/)[0];
Related
First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601
I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);
I was trying to convert a Number to Date in Javascript. Below is the code which I have tried
var newDate = new Date(1012256900000);
console.log("Test: ",newDate.toString('MMM-yyyy'));
This is working fine.
But when I get it from $rootScope object, am getting invalid date :(
var newDate = new Date($rootScope.lastLoginTime);
console.log("Test: ",newDate.toString('MMM-yyyy'));
This is printing Invalid Date. FYI,
$rootScope.lastLoginTime = 1463256900000;
Gonna take a guess here, but look at what I did in the browser console:
new Date(1463256900000)
> [date] Sat May 14 2016 21:15:00 GMT+0100
new Date("1463256900000")
> [date] Invalid date
Completely wild guess, but perhaps you should ensure you are passing a number, not a string, to new Date() - the constructor behaves very differently in either case.
Consider instead trying this:
var newDate = new Date();
newDate.setTime($rootScope.lastLoginTime);
setTime takes a numeric argument only, and will convert your string to a number for you if you pass it one.
Guess your $rootScope.lastLoginTime = '1463256900000'; than $rootScope.lastLoginTime = 1463256900000;.
new Date(time) does works when time is number , not when time is string.
var t1 = 1463256900000;
var t2 = '1463256900000';
var d1 = new Date(t1);
var d2 = new Date(t2);
console.info(d1);
console.info(d2);
I need to subtract a date like 1/26/2015 from a date-time like 2016-01-27T01:10:57.569000+00:00. From what I've read converting both to distance in milliseconds from Epoch and then subtracting is the easiest way. I've tried using various methods, but all the methods seem to say 2016-01-27T01:10:57.569000+00:00 is invalid data. The method .getTime() works great for the 1/26/2015 format, but it can't read the 2016-01-27T01:10:57.569000+00:00.
How does one go about getting the date/time UTC time into milliseconds?
On a complicated way you can use a regex to extract each part of the date as string and then use them in a new Date with all parameters:
function getTimeDifference(){
var regEx = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([\d.]+)/;
var dateString = '2016-01-27T01:10:57.569000+00:00';
var r = regEx.exec( dateString );
var date1 = new Date(r[1], r[2]-1, r[3], r[4], r[5], r[6]); // Notice the -1 in the month
var date2 = new Date('1/26/2015');
var difference = date1 - date2;
Logger.log(difference);
}
I ended up using this. When I call parseDate(), I used getTime() to get the date in milliseconds then subtracted them and converted them to days. For my use case the time didn't have to be down to the second, but if it did, it wouldn't be hard to parse more info from the string. I ran into trouble initially because as a beginner Javascript writer I didn't know why apps script wouldn't accept this format into the date constructor.
function parseDate(str) {
//This should accept 'YYYY-MM-DD' OR '2016-01-27T01:10:57.569000+00:00'
if(str.length == 10){
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
else
{
var mdy = str.split('-');
var time = mdy[2].split('T');
var hms = time[1].split(':');
return new Date(mdy[0], mdy[1]-1, time[0], hms[0], hms [1]);
}
}
If you are confident that the values in the date strings will always be valid and that the ISO8601 string will always have offset 00:00 (i.e. UTC), then simple parse functions are:
// Parse ISO 8601 format 2016-01-27T01:10:57.569000+00:00
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5],b[6]));
}
document.write(parseISOUTC('2016-02-04T00:00:00.000+00:00'));
// Parse US format m/d/y
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2],b[0]-1,b[1]);
}
document.write('<br>'+ parseMDY('2/4/2016'))
document.write('<br>'+ (parseISOUTC('2016-02-04T00:00:00.000+00:00') - parseMDY('2/4/2016')))
Note that the first string is UTC and the second will be treated as local (per ECMAScript 2015), so the difference between 2016-02-04T00:00:00.000+00:00 and 2/4/2016 will be the time zone offset of the host system.
How to convert my date to timestamp i dont know where im doing wrong.Any suggestion please ?
var dates = '27-04-2015';
var date1 = new Date(dates).getTime();
alert(date1);
Parameter you passed in the new Date('27-04-2015') is not valid. Use sepeartor '/' for change date format and send to the new Date('27/04/2015').
var dates = '27-04-2015';
var dates1 = dates.split("-");
var newDate = dates1[1]+"/"+dates1[0]+"/"+dates1[2];
alert(new Date(newDate).getTime());
Working Fiddle
Date constructor takes argument in mm-dd-yyyy format, try this
var timeStamp = function(str) {
return new Date(str.replace(/^(\d{2}\-)(\d{2}\-)(\d{4})$/,
'$2$1$3')).getTime();
};
alert(timeStamp('27-04-2015'));
Here, I had used RegExp to swap the format from dd-mm-yyyy to mm-dd-yyyy. So '27-04-2015' gives '04-27-2015'. In the expression (\d{2}\-)(\d{2}\-)(\d{4}), \d denotes integer, {} for length, () for grouping, \ to escape special characters like -.