Parsing a date in javascript - javascript

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

Related

Datetime diff in minutes

I have 2 DateTime field in a form, and I want the difference between these 2 fields in minute.
I tried to parse DateTime into Date but it's not working :
<script>
$(document).ready(function () {
$("#mybundle_evenement_button").click(function () {
var field1 = $("#mybundle_evenement_debut").val();
var field2 = $("#mybundle_evenement_fin").val();
var date1 = new Date(field1);
var date2 = new Date(field2);
alert(date1);
});
});
</script>
If I alert() date1, it shows Invalid Date.
But if I alert() field1, it shows 15/09/2017 13:32 (format is : days/months/year hour:minutes).
Is it possible that new Date(field1) isn't working because of the format ?
I know that if I succeed to parse DateTime into Date, it'll be easy to have the difference in minutes, but I don't understand why it says Invalid Date.
dd/MM/yyyy HH:mm isn't a valid date format for Date.parse()
You have to format your date to a valid Date Time String Format, for example:
var field1 = $("#mybundle_evenement_debut").val();
var ISODate1 = field1.replace(/(\d+)\/(\d+)\/(\d+)/, "$3-$2-$1")
var date1 = new Date(ISODate1);
alert(date1) // => Fri Sep 15 2017 13:32:00 ...
The problem is about the format you are getting the date from the field. new Date() don't accepts this format. I think the best is to parse the string yourself. If the format is always the same just use new Date(year, month, day, hours, minutes, seconds, milliseconds).
var day = field.splice(0,2); field.splice(0,1);
var month = field.splice(0,2); field.splice(0,1);
var year = field.splice(0,2); field.splice(0,1);
var hour = field.splice(0,2); field.splice(0,1);
var minute = field.splice(0,2);
It's depend on your browser. I'll suggest to use the standard format is '2013/12/09 10:00'.
Okay! come to the point. You need to manually format the date from my latest answer regarding this same kind of issue. Please take a look at this link : Stange javascript Date behaviour on particular dates
And you could try this below code for getting the date difference in minutes.
var startTime = new Date('2013/12/09 10:00');
var endTime = new Date('2014/12/09 10:00');
var difference = endTime.getTime() - startTime.getTime();
var result = Math.round(difference / 60000);
alert(result);

JavaScript new Date('22/22/2222') convert to a valid date in IE 11

var checkDate = new Date("22/22/2222");
When I check in IE 11 it convert to Wed Oct 22 00:00:00 EDT 2223 so my next line fails
if (checkDate != 'Invalid Date')
How to fix it?
As you've passed in an invalid date format (as far as the ECMA spec is concerned), the browser is free to choose to interpret it how it wishes. It seems IE thinks it can deal with it:
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
If you're going to pass in strange formats, you're either going to need to validate them yourself or use a library that can do so better than the browsers can.
Months and days can "wrap" in JavaScript. One way to test if the date is legal is to see if the output date corresponds to the original input string. If it doesn't, then it wrapped.
function check(inputString) {
var checkDate = new Date(inputString);
// Get month, day, and year parts, assuming
// you don't have them already
var arr = inputString.split('/');
var isMonthWrapped = +arr[0] !== checkDate.getMonth() + 1;
var isDayWrapped = +arr[1] !== checkDate.getDate();
var isYearWrapped = +arr[2] !== checkDate.getFullYear();
console.log("Parts", +arr[0], +arr[1], +arr[2]);
console.log("Results", checkDate.getMonth() + 1, checkDate.getDate(), checkDate.getFullYear());
console.log("Wrapped?", isMonthWrapped, isDayWrapped, isYearWrapped);
var isLegal = checkDate !== 'Invalid Date' && !isMonthWrapped && !isDayWrapped && !isYearWrapped;
document.body.innerHTML += inputString + ': ' + (isLegal ? 'Legal' : 'Illegal') + '<br>';
};
check("22/22/2222");
check("12/12/2222");
I think that moment.js http://momentjs.com/ is a complete and good package about dates.
You could add string date and format.
moment("12/25/1995", "MM/DD/YYYY");
And you could check if date is valid.
moment("not a real date").isValid();
See documentation
http://momentjs.com/docs/#/parsing/string-format/
You should break up your string and parse Each date to integers individually. It will be much safer.
Do something like this
var dateString = "22/22/2222";
dateString.indexOf("/");
var day = parseInt(dateString.slice(0,dateString.indexOf("/")));
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var month = parseInt(dateString.slice(0,dateString.indexOf("/")))
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var year = parseInt(dateString);
console.log(day, month, year);
var date = new Date(0);
if(month>12) console.log("hey this is totally not a valid month maaaan!")
date.setDate(day);
date.setMonth(month);
date.setYear(year);
console.log(date);

Convert milliseconds string to date in javascript

There were a lot of answered questions about converting milliseconds to date format but none of them was able to solve my problem.
I have a string (and not a time) coming in my javascript code. It is of the format as below
1380549600000+1000
When I try to parse it using the following code it gives me "invalid date" error.
My main objective is to convert this string to dd/mm/yyyy format. So was thinking of converting it into date and applying methods like "getMonth", etc
<script>
var modDate = "1380549600000+1000"; //Note the value is in "" hence a string
var d = new Date(modDate); //Invalid date error here
document.getElementById("demo").innerHTML = d;
</script>
The following works just fine. But this is not the format I am getting.
<script>
var modDate = 1380549600000+1000; //Note the value is no longer in ""
var d = new Date(modDate); //No problems here
document.getElementById("demo").innerHTML = d;
</script>
Please help.
Thanks in advance.
Cheers.
edit:-
eval is not the best approach, it is not safe to use eval, so use this instead:-
var modDate = "1380549600000+1000"
var temp = modDate.split("+");
modDate = parseInt(temp[0]) + parseInt(temp[1]);
I am not sure if you need that added 1000, if you don't, it could be done in one line as :-
modDate = parseInt(modDate.split("+")[0])
older approach :-
<script>
var modDate = eval("1380549600000+1000"); //Note the value is in "" hence a string
var d = new Date(modDate); //Invalid date error here
document.getElementById("demo").innerHTML = d;
</script>
Other approach w/o using eval:
var modDate = "1380549600000+1000";
var d = new Date(modDate.split("+")
.map(parseFloat)
.reduce(function(a,b){return a + b;}));
Use parseInt to get the numeric value of the string (safer than eval, but same premise):
modDate = (isNaN(modDate)) ? parseInt(modDate, 10) : modDate;
if !isNaN(modDate) {
var d = new Date(modDate);
document.getElementById("demo").innerHTML = d;
} else {
console.log("Value in modDate not a number");
}
I had to use a bit of a mishmash of the answers here to get mine to work.
My Date value was being sent to my web page as a String, like so: "/Date(978278400000-0500)/"
So I parsed it like this, to get it to display as a valid date:
// sDateString = "/Date(978278400000-0500)/";
var modDate = sDateString.replace(/[\/Date\(\)]/g, "");
return new Date(parseInt(modDate, 10));
//returns: Sun Dec 31 2000 11:00:00 GMT-0500 (Eastern Standard Time) {}

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Converting UTC date to mm/dd/yyyy

I am having a date in isoUtc format and I want to convert it into mm/dd/yyyy format. I tried to use the hint given in this blog entry but the problem I am facing is that if I convert 2007-04-06T00:00Z it gives different dates when user time zone is different. I want that it should give 04/06/2007 always independent of the user timezone.
Any help is appreciated
var d = '2007-04-06T00:00Z';
var d2 = d.substring(5,7)+'/'+d.substring(8,10)+'/'+d.substring(0,4);
// outputs 04/06/2007
You could thy this, if you have always constant format:
var dateString = '2007-04-06T00:00Z',
dateRegExp = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/,
match = dateString.match(dateRegExp),
date;
if (match) {
date = new Date(match[1], match[2] - 1, match[3], match[4], match[5]);
console.log(date);
}
DEMO

Categories