如何将日期选择器返回的日期格式转换为其他格式

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

本文关键字:日期 格式 转换 其他 返回 选择器      更新时间:2023-09-26

很抱歉标题不好,我不知道如何更好地表达。我会尽量解释我需要什么。

我目前正在用Javascript制作一个任务管理器(待办事项列表),在这里你可以创建任务,为它们设置时间表,然后你就会有一个列表,其中包含你需要做的所有任务以及每个任务的各自时间表(开始和结束日期)。

我正在使用Angular.jsAngular Material来完成我的UI。我有Angular Material的日期选择器。这是我用来获取日期值的代码:

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;

问题是,这个日期选择器以这种格式返回日期:"2016-04-29T08:36:10.027Z",我不想要。我想要一个更普通的格式,比如"DD-MM-YYYY"。

我尝试用Moment.js转换日期格式,但没有成功。这是我使用的代码:

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

然后我会将该日期存储在本地存储:

// 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));

使用该代码,我在尝试将新任务添加到任务列表时会得到"无效日期"。

抱歉发了这么长的帖子!

感谢任何能帮助我的人。

您可以使用以下代码使用angular material datepicker转换html中的日期格式。

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

使用角度日期过滤器格式化日期。参考链接角度日期

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

在控制器主模块中注入$filter。

处理日期的最佳方法是使用momentjs,并且有一个特殊的AJS指令可用。角力矩您可以查看[momentjs][2]官方文档以了解详细信息。您必须添加angular-moment作为依赖注入,才能轻松使用moment。https://github.com/urish/angular-moment#instructions-用于将即时时区与webpack 一起使用