Reputation: 826
I'm having trouble getting the hour and minute portions from the datetime field on the form.
var date = Xrm.Page.data.entity.attributes.get("createdon").getValue();
I can use getDate(), getMonth() and GetFullYear() methods on the returned object, but I cannot get the hour and minute data. The date object shows "Tue Dec 25 11:47:44 UTC+0200 2012", so the time is there. Is the only way to get hour/minute to do some ugly substring operations on that value?
Thanks in advance.
Upvotes: 3
Views: 12629
Reputation: 73
var DateTimeFormatString ="hh:MM:ss";
// Formats the date to CRM format
function dateToCRMFormat(date) {
return dateFormat(date, DateTimeFormatString );
}
// Formats the date into a certain format
function dateFormat(date, format) {
var f = "";
try {
f = f + format.replace(/dd|mm|yyyy|MM|hh|ss|ms|APM|\s|\/|\-|,|\./ig,
function match() {
switch (arguments[0]) {
case "dd":
var dd = date.getDate();
return (dd < 10) ? "0" + dd : dd;
case "mm":
var mm = date.getMonth() + 1;
return (mm < 10) ? "0" + mm : mm;
case "yyyy": return date.getFullYear();
case "hh":
var hh = date.getHours();
return (hh < 10) ? "0" + hh : hh;
case "MM":
var MM = date.getMinutes();
return (MM < 10) ? "0" + MM : MM;
case "ss":
var ss = date.getSeconds();
return (ss < 10) ? "0" + ss : ss;
case "ms": return date.getMilliseconds();
case "APM":
var apm = date.getHours();
return (apm < 12) ? "AM" : "PM";
default: return arguments[0];
}
});
}
catch (err) {
}
return f;
}
For testing
var time= Xrm.Page.getAttribute("createdon").getValue();
alert("Time: " + dateToCRMFormat(time));
Upvotes: 3
Reputation: 39298
You could use getHours and getMinutes on the Date object.
var date = new Date();
var time = date.getHours() + ":" + date.getMinutes();
Now, you only need to substitute the value for date as it in my example is the current point of time and you're fetching it from a field.
You might want consider shortening your syntax as well. I'm not in front of the computer at the moment (not that computer, that is), but I believe that you can go like this instead.
var date = Xrm.Page.getAttribute("createdon").getValue();
It's amazing - no matter how much JavaScript one codes. Five minutes later, everything is gone from the mind. It's like if the syntax is intended to be memory resistant. :)
You should not be playing around with substring nor regex. JavaScript source code tends to be ugly and confusing the way it is already. No point making it worse and less comprehensible.
And as for the regular expressions - a programmer had a problem to solve. So he thought - "I know, I'll use RegEx". Then he had two problems.
Upvotes: 3