简体   繁体   中英

How do I convert datepicker returned date format to a different format?

Sorry about the bad title, I didn't exactly know how to phrase that any better. I'm going to try to explain what I need as best as possible.

I'm currently making a Task Manager (a ToDo list) in Javascript where you can create tasks, set a schedule for them and then you would have a list with all the tasks that you need to do and the respective schedule of each task (beginning and ending date).

I'm using Angular.js and Angular Material to do my UI. I have the Angular Material's datepicker. This is the code I use to get the date value:

angular.module('KBTM_App', ['ngMaterial']).controller('AppCtrl', function($scope) {
$scope.myDate1 = new Date();

...

// This is where I get the date value
var initial_date_1 = angular.element(document.querySelector('[ng-controller="AppCtrl"]')).scope().myDate1;

The problem is that this datepicker is returning the date in this format:"2016-04-29T08:36:10.027Z", which I don't want. I want a more normal format, like "DD-MM-YYYY".

I tried converting the date format with Moment.js , but that didn't work. Here's the code I used for that:

var initial_date = moment(initial_date_1, "YYYY-MM-DD'T'HH:MM:SS.SSS'Z'").format("DD-MM-YYYY");

And then I would store that date in the localStorage:

// Get the other dates already in the list
var initial_dates = get_initial_dates();

// Adds the new date to that list
initial_dates.push(initial_date);

// Stores those dates in the localStorage
localStorage.setItem('initial_date_db', JSON.stringify(initial_dates));

With that code I get " Invalid date " when trying to add a new task to the task list.

Sorry for the long post!

Thanks to whoever can help me.

您可以使用以下代码使用角材料datepicker转换html中的日期格式。

 data-ng-value="myDate1  | date : 'shortDate'"

Use the angular date filter to format the date. Refer the link angular date

var  initial_date = $filter('date')($scope.myDate1, "dd-MM-yyyy");

Inject the $filter in your controller main module.

Best way to handle dates is to use momentjs and there is a special AJS Directive available. angular-moment You can check [momentjs][2] offical docs for detailed info. You have to add angular-moment as dependency injection to use moment easily. https://github.com/urish/angular-moment#instructions-for-using-moment-timezone-with-webpack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM