Eg. Text box requires me to enter a date. If i type in "Sep 1,2016" and "Sep 3,2016" and "Sep 4,2016" It must be convert and displayed as 1/10/16 - 4/10/16. How do i do this?
-
Have a look to bootstrap datepicker or jquery ui date picker or moment.js – Weenesta - Mathieu Dormeval Nov 25 '16 at 15:59
-
1Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Kevin Kloet Nov 25 '16 at 16:00
1 Answers
Your question in the title is different from the one in the description.
Converting a string format "Sep 1,2016"
to "09/01/16"
should be achievable by using:
> "Sep 1,2016".split(/[\s,]+/);
[ 'Sep', '1', '2016' ]
Use an array to determine the month numbers:
var months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var monthDigit = months.indexOf("Sep") + 1;
...therefore:
> months.indexOf("Sep") + 1;
9
To add a 0 prior to a single-digit month or day:
var month = "9";
if (month.length === 1) {
month = "0" + month;
}
To get the last two digits of a year, do:
var myYear = "2016";
myYear = myYear.slice(-2);
Once you have your final object, ["09", "01", "16"]
, all you have to do is use the .join("/");
function to put them in the proper format, the result being "09/01/16"
If you want to order the dates, as asked in the title, you'd have to format the date in a YY/MM/DD format and then sort the strings.
Sorting dates: https://stackoverflow.com/a/30691186/7207316
The Simple Solution
There is no need to convert Strings to Dates or use RegExp.
The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});
Run Snippet to Test
<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});
for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

- 1
- 1

- 11
- 4