I need to convert date '02-01-2017' to '2017-01-02'.How can I do this in angularjs.Please help me.Thanks in advance.
Asked
Active
Viewed 392 times
2 Answers
0
This should do,
var date = "02-01-2017";
var newdate = date.split("-").reverse().join("-");
console.log(newdate);
DEMO
var date = "02-01-2017";
var newdate = date.split("-").reverse().join("-");
console.log(newdate);

Sajeetharan
- 216,225
- 63
- 350
- 396
0
You can use angular js date filters for this purpose. The date filter syntax is like
{{ date | date : format : timezone }}
where format is your required format i.e, yyyy-dd-MM
and timezone that you prefer. You can find examples for this here and documentation at
angular js website
In chrome you can directly use new Date('02-01-2017');
but in firefox there are some compatibility issues so that the date string needs to be written as new Date('02/01/2017');
this will support in chrome also. Your date time stamp needs to be "IETF-compliant RFC 2822 timestamp". You can find the details regarding the compatibility issues here.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date In Chrome {{ date | date:"yyyy-dd-MM" }}</p>
<p>Date In FireFox {{ dateFF | date:"yyyy-dd-MM" }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function ($scope) {
var dateTimeString = '02-01-2017';
$scope.date = new Date(dateTimeString);
$scope.dateFF = new Date(dateTimeString.replace("-", "/"));
});
</script>
<p>The date filter formats a date object to a readable format.</p>
</body>
</html>
-
1invalid date string format for `new Date()`. try it in firefox for example ...returns `invalid date`. This answer fails cross browser – charlietfl Jan 02 '17 at 05:00
-
@charlietfl In firefox there are some compatibility issues so that the date string needs to be written as new Date('02/01/2017'); this will support in chrome also. – Nitheesh Jan 02 '17 at 05:14
-
1It's not a firefox issue, or even a browser issue...it's a spec issue of using invalid string format. And you have to parse the string to get that...which your edit does not do. You just magically made it appear in controller – charlietfl Jan 02 '17 at 05:15
-
-
That makes no sense whatsoever. It needs to be a valid string per Date docs. How are you going to test the many hundreds of possible browsers? You completely missed the whole point – charlietfl Jan 02 '17 at 05:23
-
the below line is replacing for ones like this 01/01-2017 dateTimeString.replace("-", "/") how to resolve this issue – Mr. Lucifer Jun 17 '17 at 09:46