Formatted date not coming proper in Safari Browser - javascript

I am trying to run the below code in Safari browswer but the date is not coming properly in the alert box. It shows correct date in Google chrome. In safari it shows " Tuesday 23rd March, 2015 " and in Chrome it shows " 23 Mar 2015".
Does anyone knows why it is happening?
function getFormattedDate(input){
var pattern=/(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Dec'];
return (p2<10?"0"+p2:p2)+" "+months[(p1-1)]+" "+p3;
});
alert(result);
}
d1= new Date();
d2= d1.toLocaleDateString();
alert(d2);
getFormattedDate(d2);

Refer to this thread.
toLocaleDateString() is not returning dd/mm/yyyy format
You can use this code adopted from the answer written by Niet the Dark Absol adapted for you.
function getFormattedDate(input){
var pattern=/(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Dec'];
return (p2<10?"0"+p2:p2)+" "+months[(p1-1)]+" "+p3;
});
alert(result);
}
var dateobj = new Date();
function pad(n) {return n < 10 ? "0"+n : n;}
var d2 = pad(dateobj.getMonth()+1)+"/"+pad(dateobj.getDate())+"/"+dateobj.getFullYear();
alert(d2);
getFormattedDate(d2);

Related

Why does Ionic-2 Calendar gives "Invalid Date" after passing to js Date() and when calling onViewTitleChanged?

I am trying to figure out why I keep getting an "Invalid Date" after passing it to var sDate = new Date(title). My goal is to only get the current month, so I could query it on sqlite.
Using ionic 4, ionic2-calendar and angular on ionic-cordova.
I have the following ionic2-calendar method.
onViewTitleChanged(title)
{
console.log("onViewTitleChanged:")
console.log(title)
var sDate = new Date(title)
console.log("check Date:")
console.log(sDate)
console.log("typeof:")
console.log(typeof title);
}
Which outputs the following.
onViewTitleChanged:
May 2020
check Date:
Invalid Date
typeof:
string
I tried to run a single file date.js and tried to run on node.
node date.js
And gives the following output.
sDate:
2020-04-30T16:00:00.000Z
I also tried to run a code-snippet, works fine. But on the ionic-device, it does not?
var title = "May 2020"
console.log("onViewTitleChanged:")
console.log(title)
var sDate = new Date(title)
console.log("check Date:")
console.log(sDate)
console.log("typeof:")
console.log(typeof title);
I could not get why it does not work on the emulator (iOS), debugging using Safari nor the device.
This is what I did to resolve my issue. Thanks for the suggestion that I should pass a valid ISO 8601 on Safari.
My solution was just to split the passed Month and Year and re-formatted it.
// Passed Month, Year Only
var title = "May 2020"
// Split Ionic Month and Year
var sd = title.split(" ")
// Format to Proper Date
var pd = sd[0] + ' 1, ' + sd[1]
var sDate = new Date(pd)
console.log("Proper Date Parsed:")
console.log(sDate)
var month = '0' + (sDate.getMonth() + 1);
var year = sDate.getFullYear();
console.log("Month(slice):" + month.slice(-2))
console.log("Year(slice):" + year)
Works now.

Parsing a date in 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

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) {}

new Date is not working on Firefox

Can you tell me why this is not working on Firefox (V 34 latest) ? It's working fine on all other browsers. 'DatePosted' is shown as Invalid Date.Why ? Any help would be highly appreciated.
//Get local time for everything:
data.Comments.forEach(function (x) {
x.DatePosted = new Date(x.DatePosted.toString().replace("T", " ") + " UTC");
});
Note : x.DatePosted : "2014-11-18T08:06:39.06"
You dont need to replace the T. It works without it (tested in Chrome and Firefox).
After setting the Date object, get it into UTC.
Working snippet below:
var myDate = new Date("2014-11-18T08:06:39.06");
// now set it to UTC
var myDateinUTC = Date.UTC(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());
console.dir(myDateinUTC);
var myNewDate = new Date(myDateinUTC);
console.log(myNewDate.getMonth()); // just to test

Change date format in javascript

I have an example which finds the difference of days between 2 specified dates and works only in Chrome, I think in firefox 6 and IE8 it does not support the format of date that I am using (shows NaN). Can somebody help me change the format to desired 1 (see below)?
Here is my DEMO
My format : 2011-08-18 11:49:01
Desired format : 08-18-2011 11:49:01
My Code
var cellvalue="2011-08-18 11:49:01.0 IST";
var firstDate = new Date();
var secondDate = cellvalue.substring(0, cellvalue.length-4);
alert(diffOf2Dates(firstDate,secondDate));
function diffOf2Dates(todaysDate,configDate)
{
/*var udate="2011-08-18 11:49:01.0";
var configDate=new Date(udate);*/
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = todaysDate; // Todays date
var secondDate = new Date(configDate);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return Math.ceil(diffDays);
}
I used the Datejs library with great results when having to work with dates in various formats. Give it a go: http://www.datejs.com

Categories