CDate for Javascript - javascript

I have been using CDate in my program and the worry part is , it works only in IE.
cdate(strValue) . If I pass the value of strvalue as 01/02 , it returns as Wed Jan 2 etc . Am looking for the same implementation in javascript so that it will work in other browsers. Am trying my best to find one, but am not lucky. Can anyone tell me what api we can use in javascript instead of using CDate ??

You can try the following code:
var comp = "05/04".split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var date = new Date(null, m - 1, d);
date.toDateString(); //this line will return the date
Now you can parse the string and manipulate string according to your need.

Related

Split datetime of api response

I'm getting info from an API, and what I want to do is get the response of date time. This is part of my code:
function perDetail(){
$http.get('/api/values')
.then(function(data){
$scope.details = data.data.Response;
});
}
Part of what i get is:
"Date":"2018-07-16T18:00:00"
And what I wanna do is get the hour:
18:00
Someone can guide me, please? I know there's a split and splice method, but I can't get the value. Maybe sounds too easy but right now, I'm stuck with this.
I'm using AngularJs and Javascript.
Thanx in advance.
Here's one way to do it.
var date = "2018-07-16T18:00:00";
var time = date.split("T")[1]; // time is "18:00:00"
var justHour = time.slice(0, 5); //from index 0 to index 5 (first 5 characters)
return justHour; //"18:00"
If I understood correctly, "Date" is a key in the response object you are getting from your API call, right? And you just want to get the hours:minutes part in the corresponding value?
If that's correct, I think slicing the value in the right places would do the job:
data["Date"].slice(-8, -3)
You can have only HH:MM by converting String date to Date and get required fields. Below are several ways.
var date = "2018-07-16T18:00:00";
var mydate = new Date(date);
console.log(mydate.getHours());
console.log(mydate.getMinutes());
console.log(mydate.toTimeString());
console.log(mydate.toTimeString().split(" ")[0]);
console.log(mydate.getHours(),":",mydate.getMinutes());
console.log(mydate.toTimeString().replace(/.*(\d{2}:\d{2})(:\d{2}).*/, "$1"));
Have you tried using getHours(), getMinutes(), getSeconds() functions? You can combine results and get time.
var d = new Date("July 21, 1983 01:15:00");
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
Source: https://www.w3schools.com/jsref/jsref_gethours.asp

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

javascript Date object create using string from input

I've got a problem with date object in IE8, and some older browsers. On website I have input hidden, where I keep date, and after change new date should be in that field.
On my machine everything is fine, but on some others I get NaN-NaN-NaN, that's my code:
var date = new Date($('#curDate').val());
//date.setDate(date.getDate() - 7);
var dateMsg = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
alert(dateMsg);
When I run this file (php), in hidden input I've got Monday's date from the current week 2013-03-25.
This alert return me NaN-N.. on Win XP IE8, and on very old mac, I recon it's problem with object. How to take date value and convert it to object in javascript?
Never use new Date(some_string) - it's unreliable because it depends on the user's locale.
Break the string into its yy/mm/dd components yourself and then call new Date(y, m - 1, d)
Problem with your hyphens..
Convert your hyphens('-') with slashes('/')
var dateStr=$('#curDate').val();
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
or
var date=new Date(convertToSlash($('#curDate').val()));
function convertToSlash(string){
var response = string.replace(/-/g,"/");
return response;
}
You can also use new Date(some_string) format. It's reliable. However, the datestring must be in ISO format that is yyyy/mm/dd.

Javascript JSON Date parse in IE7/IE8 returns NaN

I'm parsing a date from a JSON event feed - but the date shows "NaN" in IE7/8:
// Variable from JSON feed (using JQuery's $.getJSON)
var start_time = '2012-06-24T17:00:00-07:00';
// How I'm currently extracting the Month & Day
var d = new Date(start_time);
var month = d.getMonth();
var day = d.getDate();
document.write(month+'/'+day);// "6/24" in most browsers, "Nan/Nan" in IE7/8
What am I doing wrong? Thanks!
In older browsers, you can write a function that will parse the string for you.
This one creates a Date.fromISO method- if the browser can natively get the correct date from an ISO string, the native method is used.
Some browsers got it partly right, but returned the wrong timezone, so just checking for NaN may not do.
Polyfill:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Result:
var start_time = '2012-06-24T17:00:00-07:00';
var d = Date.fromISO(start_time);
var month = d.getMonth();
var day = d.getDate();
alert(++month+' '+day); // returns months from 1-12
For ie7/8 i just did:
var ds = yourdatestring;
ds = ds.replace(/-/g, '/');
ds = ds.replace('T', ' ');
ds = ds.replace(/(\+[0-9]{2})(\:)([0-9]{2}$)/, ' UTC\$1\$3');
date = new Date(ds);
This replaces all occurrences of "-" with "/", time marker "T" with a space and replaces timezone information with an IE-friendly string which enables IE7/8 to parse Dates from Strings correctly. Solved all issues for me.
See RobG's post at Result of toJSON() on a date is different between IE8 and IE9+.
Below function worked for me in IE 8 and below.
// parse ISO format date like 2013-05-06T22:00:00.000Z
function convertDateFromISO(s) {
s = s.split(/\D/);
return new Date(Date.UTC(s[0], --s[1]||'', s[2]||'', s[3]||'', s[4]||'', s[5]||'', s[6]||''))
}
You can test like below:
var currentTime = new Date(convertDateFromISO('2013-05-06T22:00:00.000Z')).getTime();
alert(currentTime);
I suggest http://momentjs.com/ for cross browser date issues.
#gib Thanks for the suggestion on Moment.js. This small library really helps out with dealing with dates and JavaScript.
Moment.js solved the problem described in the original question that I was also having. IE8 was displaying JSON ISO dates as NaN when parsed into a new Date() object.
Quick solution (include moment.js in your page, or copy the code to your js functions include)
If you just need to display a date on your page, loaded from a JSON ISO date, do this:
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.calendar()); //use Moment's relative date function to display "today", "yesterday", etc.
or
order_date = moment(data.OrderDate); //create a "moment" variable, from the "data" object in your JSON function in Protoype or jQuery, etc.
$('#divOrderDate).html(order_date.format('m/d/YYYY')); //use Moment's format function to display "2/6/2015" or "10/19/2014", etc.
If you must have a Date() object (say for use with jQuery Components), do the following so successfully populate your JSON provided ISO date. (This assumes you are already inside the function of handling your JSON data.)
var ship_date = new Date(moment(data.ShipDate).format('m/d/YYYY')); //This will successfully parse the ISO date into JavaScript's Date() object working perfectly in FF, Chrome, and IE8.
//initialize your Calendar component with the "ship_date" variable, and you won't see NaN again.

Categories