How to format Date in Angular Java script?
Code
<p id="summaryHeader">Calendar of {{dt}}</p>
I get the value as
2014-06-05T12:38:42.744Z
I tried this
<p id="summaryHeader">Calendar of {{dt|date:'MMMM dd'}}</p>
which gives me
Calendar of June 05
I need it as Calendar of June 05th or July 2nd and so on.. the rear rd,th,st is what I am looking for.
Anuglar Docs are good but don't specify this formatting.
I guess this is what you are looking for - http://www.michaelbromley.co.uk/blog/13/an-ordinal-date-filter-for-angularjs
A custom filter using the logic
app.filter('dateSuffix', function($filter) {
var suffixes = ["th", "st", "nd", "rd"];
return function(input) {
var dtfilter = $filter('date')(input, 'MMMM dd');
var day = parseInt(dtfilter.slice(-2));
var relevantDigits = (day < 30) ? day % 20 : day % 30;
var suffix = (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
return dtfilter+suffix;
};
});
And a Demo: http://plnkr.co/edit/HiyQ9uvxQL3FRoj7hKB8?p=preview
I wanted to have the ordinal indicator as a superscript, so used the following:
<div>{{amount}}<sup ng-bind="amount | ordinal"></sup></div>
Using the filter:
app.filter('ordinal', function() {
return function(number){
if (isNaN(number) || number < 1){
return '';
} else if (number % 100 == 11 || number % 100 == 12) {
return 'th';
} else {
var lastDigit = number % 10;
if (lastDigit === 1) {
return 'st';
} else if (lastDigit === 2) {
return 'nd';
} else if (lastDigit === 3) {
return 'rd';
} else if (lastDigit > 3) {
return 'th';
}
}
}
});
Note that this correctly renders 11th, 12th, 111th, 1012th, and not 11st.
You are correct that the date filter does not provide this formatting... I would suggest that you either write your own filter, or just do this:
Calendar of {{dt|date:'MMMM dd'}}{{getOrdinal(dt)}}
if you write your own, I would start with the one from angular as a baseline.
EDIT the idea of writing your own in the answer provided by guru is the approach I would take.
To expand upon the example he created, I would tweak it so that you can use this syntax:
Calendar of {{dt|date2:'MMMM ddoo'}}
Where oo is the ordinal suffix
I updated this representative plnkr to give you maximum flexibility.
For anybody that hits this question there is the project https://github.com/chrisiconolly/angular-all-ordinal-filters (full disclaimer: my own project) that will give you a ordinal number filter for angular.
Its used as so:
{{number | ordinal}} // 1 -> 1st
{{number | ordinalOnly}} // 1 -> st
It's fully tested and running through travis so it will remain stable.
You could wrap your date in a momentjs object like
$scope.dt = moment($scope.dt);
then do
<p id="summaryHeader">Calendar of {{dt.format("ddd Do")}}</p>
Other options may be better unless you already use momentjs elsewhere, just an option.
While not my best work you can start with this as a baseline
http://plnkr.co/edit/v2RuF72A9OPpFj5fvN8A?p=preview
Related
var dayInput = document.querySelector("#day");
var monthInput = document.querySelector("#month");
var yearInput = document.querySelector("#year");
var day = document.querySelector("h2");
var h3 = document.querySelector("h3");
function runCode() {
dayPicked = Number(dayInput.value);
monthPicked = Number(monthInput.value);
yearPicked = Number(yearInput.value);
if (dayPicked <= 31) {
if (monthPicked <= 12) {
if ((monthPicked = 2) && (dayPicked <= 29)) {
day.textContent = (DispDay(dayPicked, monthPicked, yearPicked));
h3.textContent = (DispFullDate(dayPicked, monthPicked,
yearPicked));
} else { day.textContent = "Not Possible Dude!"}
} else { day.textContent = "Not Possible Dude!"}
} else { day.textContent = "Not Possible Dude!"}
}
This is a snippet out of my code where I am trying to limit the search for dates within my input boxes. For example, if February is chosen and the day is the 30th, it should throw out an error. But all that happens with the code you see above is no matter what month I choose, it keeps returning February. I know I am definitely doing something wrong, but I do not know what it is. BTW - I started learning JavaScript 3 weeks ago so I know my code is a mess. Thanks.
var button = document.querySelector("#goButton");
[dayInput, monthInput, yearInput].forEach(function (element) {element.addEventListener("keyup", function (event) {
event.preventDefault();
if (event.keyCode === 13) {
runCode();
}
});
});
I don't know if the EventListener needs to be added here but here it is anyway.
You're setting monthPicked
monthPicked = 2
You meant to use two == to check for equality.
However, the next problem you'll see is that your code will only work if the user selects February.
You probably wanted
if ((monthPicked != 2) || (dayPicked <= 29)) {
That way if they select february, it has to be before 29th. Any other month can be anything. Still incomplete logic as some months should allow 31 others not. But i'll leave that to you. (Also, leap years!)
= is an Assignment Operator. == is an Equal To Operator,compares value of left and side expressions. Change monthPicked = 2 to monthPicked == 2.
I have a json file that has a string as the pubDate. The pubDate could be 2010 or 2010 Mar or 2010/1/1 or Blank or Not available. What I have is
var res = pubDate.substr(0, 4);
var i = parseInt(res, 10);
if (!isNaN(i)) {
if (i > 2010) {
//do work
}
}
This works but I'd love to have some cleaner code where I might be able to do it in one or two lines of code. This this possible?
1) If i is NaN, i > 2010 will be false, so the isNaN check is not neccessary.
2) ParseInt ignores suffix characters, so you don't have to substr:
const year = parseInt(pubDate);
if(year > 2010) {
//...
}
That's a pretty messy situation it sounds like, short of collapsing some of those lines I don't think you have much of an option. By collapsing some of the lines I mean literally:
var i = parseInt((pubDate.substr(0, 4), 10);
if (!isNan(i) && i > 2010) {
// do work
}
But this is assuming you don't need "res" for something later, which looks like you shouldn't.
Maybe two lines of code. Maybe not cleaner code.
var i = (!isNaN(parseInt(pubDate.substr(0, 4))))?parseInt(pubDate.substr(0, 4)):0;
if( i > 2010 ){
//do work
}
If you are not looking for decimal specific you could remove the 10. More information about this on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var i = parseInt(pubDate.substr(0, 4));
if (!isNaN(i) && i > 2010) {
//do work
}
Stuck on the thinking of this, a user can enter a time into a field in the formats listed below. The time in the end will be saved and formatted to xx:xx 12 hour. I'm allowing flexibility/laziness on the user's part rather than throw strict errors.
Formats Allowed
1 (1 digit)
11 (2 digits)
11 1(hours and min)
11 10(hours and mins)
1110(hours and mins, no space)
Problems
I need to somehow take the user's entered time
Add prefixed zeros where needed so i get (xx:xx)
Add ":" in between hours and mins
Why do I need specifically ":" inserted? I need to save hour and min into separate variables later but I need to reformat the time behind the scenes so that it's ALWAYS xx:xx, having it in a predictable format means I can use JavaScript to split it by the ":" and do what I need to from there.
I'm not looking for the straight answer so much as suggestions because I'm under the assumption i'll need regex.
http://jsfiddle.net/8dabu7d8/7/
var number = "11 11";
console.log(format(number));
function format(number) {
if (number.length == 1 ) {
return '0' + number + ':00'
}else if (number.length == 2) {
return number + ':00'
} else if (number.length == 3){
return number.substring(0, 2) + ':' + number.substring(2)
} else if (number.length == 4 || number.length == 5){
return number.substring(0, 2) + ':' + number.substring(2).trim()
}
}
Using the replace method, you could do something such as :
var myRegexp = /(\d{1,2})[ ]?(\d{0,2})/i;
var match = myRegexp.exec(yourString);
var result = match[1];
if(match[1].length == 1)
{
result = match[1].concat("0");
}
result = result.concat(":");
if(match[2].length != 2)
{
if(match[2].length == 0){
result = result.concat("00");
}
else{
result = result.concat(match[1].concat("0"));
}
}
My suggestion is to use a time picker which will solve all your overheads and the user experience will also be great.You have a enormous time picker controls available in java script.
here is a simple example
http://jonthornton.github.io/jquery-timepicker/
I feel better to use any of these time picker control.
I am quite new to Grails and in an application I need to check dates. In a former Java program I have used two javascript functions with different detail granularity. Both accept dates from 1970-01-01 to 2099-12-31. One demands a correct date and (optionally) time and just tells the user he/she made an erroneous entry:
function okdate1(dtstr) {
var ok = true;
// First trim off leading and trailing white space
var trimPattern = /(?:\b(.*)\b)/;
dtstr = (dtstr.match(trimPattern))[1];
// Verify that input is within range and correct
var pat = /^((?:19[7-9][0-9])|(?:20[0-9][0-9]))-((?:(?:0)?[1-9])|(?:1[0-2]))-((?:(?:0)?[1-9])|(?:[1-2][0-9])|(?:3[01]))(?: ((?:(?:0|1)[0-9])|(?:2[0-3])):([0-5][0-9]))?$/;
var dtm = dtstr.match(pat);
if (!dtm) {
ok = false;
} else { // Verify that day in in range for the given month
var days = Array(31,28,31,30,31,30,31,31,30,31,30,31);
// Compensate for leap year
if ((((dtm[1] % 4) === 0) && !((dtm[1] % 100) === 0)) || ((dtm[1] % 400) === 0)) {
days[1] = 29;
}
if (dtm[3] > days[dtm[2] - 1]) ok = false;
}
if (!ok) alert("Enter date and (optionally) time on the form 'yyyy-MM-dd HH:mm'");
return ok;
}
and the other that checks exactly what went wrong by accepting a wider range on the numeric parts of the input string:
function okdate2(dtstr) {
// First trim off leading and trailing white space
var trimPattern = /(?:\b(.*)\b)/;
dtstr = (dtstr.match(trimPattern))[1];
// If nothing then skip the rest
if (!dtstr) return datetimealert(0);
// Pattern to recognize any 'dddd-dd-dd[ dd:dd]' pattern
var pat = /^(?:(\d{4})-(\d{1,2})-(\d{1,2}))(?: (\d{1,2}):(\d{2}))?$/;
var dtm = dtstr.match(pat);
// If this is does not follow the pattern: get out
if (!dtm) return datetimealert(0);
// convert each group to a number
// if no time notation the corresponding groups become NaN
for (var i = 1; i < dtm.length; i++) {
dtm[i] = Number(dtm[i]);
}
// Check for correct year interval
if (dtm[1] < 1970 || dtm[1] > 2099) return datetimealert(1);
// Check for correct month notation
if (dtm[2] < 1 || dtm[2] > 12) return datetimealert(2);
// Array with correct numer of days for each month
var mdays = Array(31,28,31,30,31,30,31,31,30,31,30,31);
// Compensate for leap year
if ((((dtm[1] % 4) === 0) && !((dtm[1] % 100) === 0)) || ((dtm[1] % 400) === 0)) {
mdays[1] = 29;
}
// Check the day for the given month
if (dtm[3] < 1 || mdays[dtm[2] - 1] < dtm[3]) return datetimealert(3);
// If only date was given and no time, we are OK
if (isNaN(dtm[4]) && isNaN(dtm[5])) return true;
// This can not happen according to pattern, but ...
if (isNaN(dtm[4]) || isNaN(dtm[5])) return datetimealert(4);
// check given hour
if (dtm[4] > 23) return datetimealert(5);
// Check given minutes
if (dtm[5] > 59) return datetimealert(6);
// If no error
return true;
}
where the function datetimealert puts out an alert with a (hopefully) good error message and returns false. The 'trimpattern' in both function strip leading and trailing whitespace.
I used them in my forms where I made calls to them in an "onsubmit" function. My objective here is not to discuss the two functions but comments on them are, of course, welcome.
In my Grails application I use jQuery datepicker extended with Trent Richardsons jQuery timepicker addon, so I get a text string as a result. I call the datetimepicker in a form:
<form ...
<dl ...
<dt>Start date <span class="required-indicator">*</span></dt>
<dd>
<div class="fieldcontain ${hasErrors(bean: todoInstance, field: 'startdate', 'error')} required">
<g:textField name="startdate" id="datepicker" class="datepicker"
value="${formatDate(format:'yyyy-MM-dd HH:mm',date:todoInstance?.startad)}" required="" />
</div>
</dd>
...
For all the other 'required' fields I get a little 'tooltip'-like message telling me to
enter a value into the field.
Now, I want to use my two datetime javascript in my grails application but I don't want alert boxes popping up, I want to use them in the static-constraints section in the domain classes and get my messages in the same manner as for the other fields. How do I integrate them into the error management system i grails?
This error messages are provided by the validation API. To inplement your own customized validations you can use the constraint validator.
But I'm assuming that you already declared your field as java.util.Date in the domain class, so you need a Date object in the validator. By default, Grails handle dates with g:datePicker, that will split the date in day, month and year fields.
To bind a single String with some format to a date object, you can register a custom Date Property Editor, like this example.
The Grails validation API is for server side validation. In your case one option is the JQuery Validation UI Plugin, that provides client side validation through JQuery. The plugin supports all standard constraints and you can create your own validations (like your date validations), checkout the extensibility docs session.
I have a datatable I'm using which has 5 columns ( http://datatables.net/ )
The columns are
Date in format of: Jan 5
Time in format of: 10:31 AM (xx:xx XX)
Columns 3, 4, 5 aren't important, they're just data that I dont care about the sorting as long as 1 & 2 are correct.
I want to sort by Date FIRST (most recent), then I want to sort by Time (most recent at top).
So Jan 5, 4:58 PM should show before 4:58 AM, and obviously all the other numbers need to work as well for all other times. The format is always the same, ie: 12:34 AM, 4:15 PM, 12:00 AM, etc.
For the date, that already works perfectly. There's only 2 days of data max in the datatable, so even when it rolls over to the 1st of the month, that will still show at the top which is fine. I have looked at the documentation and I'm confused how to do the correct sorting for my Time column.
Here is my code:
oTable = $('#posts').dataTable({
"bSort": true,
"aaSorting": [ [0,'desc'], [1,'asc'] ],
"aoColumns": [
null,
{ "sType": 'time-sort' },
null,
null,
null
]
});
This is from here: http://datatables.net/release-datatables/examples/basic_init/multi_col_sort.html
I take it now I have to build some sort of custom sorting algorithm for time using the sType property for "aoColumns" (you can see it in the example link above where he sorts case sensitively), and I have zero idea how to do this :( I'm not quite even sure if I did this right so far. It seems to sort the two columns fine, but now I need to make it so time is proper...
Here is the other part of the code that I believe I need. (once again, this is from the example). I'm 99% sure this is where I need to put in my custom time sorting code for both ascending and decending.
/* Define two custom functions (asc and desc) for time sorting */
jQuery.fn.dataTableExt.oSort['time-sort-asc'] = function(x,y) {
return ???;
};
jQuery.fn.dataTableExt.oSort['time-sort-desc'] = function(x,y) {
return ???
};
You can do this by parsing the time from your input string into a date object and then comparing the date objects:
Working Demo here: http://live.datatables.net/erefom/2/edit#preview
Source here: http://live.datatables.net/erefom/2/edit
Also see this answer: What is the best way to parse a time into a Date object from user input in Javascript?
Elaborating from earlier examples; following snippet will sort even if the time cell is empty.
function getTimeValue(x) {
// if the cell is not empty then parse it, otherwise just return 0 as the value; so it will be sorted appropriately.
if (x != '') {
var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/);
var h = parseInt(time[1]) + (time[3] ? 12 : 0);
if(!time[3] && parseInt(time[1])==12) h = 0;
if(time[3] && parseInt(time[1])==12) h = 12;
return h * 60 + ( parseInt(time[2]) || 0 );
} else {
return 0;
}
}
This is what worked for me
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"time-sort-pre": function(a) {
if (a == '')
return null;
var time = a.match(/(\d+)(:(\d\d))?\s*(p?)/i);
if (time == null)
return null;
var hours = parseInt(time[1], 10);
if (hours == 12 && !time[4]) {
hours = 0;
}
else {
hours += (hours < 12 && time[4]) ? 12 : 0;
}
var d = new Date();
d.setHours(hours);
d.setMinutes(parseInt(time[3], 10) || 0);
d.setSeconds(0, 0);
return d;
},
"time-sort-asc": function(a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"time-sort-desc": function(a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
using a piece of code from this answer What is the best way to parse a time into a Date object from user input in Javascript? and tested with dataTables 1.9.4, this code need to be called after the dataTables.js as a plugin, then just need to set de sType to your column {sType: "time-sort"}. Example:
$('#datatable-list').dataTable(
aoColumns: [{sType: "time-sort"}]
);
Assuming that your table only have one column with the time values