简体   繁体   English

如何将日期格式从dd / mm / yyyy更改为MM / dd / yyyy,其中日期已从字符串转换?

[英]How to change format of a date from dd/mm/yyyy to MM/dd/yyyy where date is already converted from string?

I am getting date from a API which is in string format, I converted that string to date but unable to change it's format. 我从字符串格式的API获取日期,我将该字符串转换为日期,但无法更改其格式。 Currently I got string like this -> '20/11/2016' I want to convert this & should look like this -> 11/20/2016 & then only I can display this in html page using html 5 date input type 目前我有这样的字符串-> '20 / 11/2016'我想转换为它并应该看起来像这样-> 11/20/2016&然后只有我可以使用html 5日期输入类型在html页面中显示它

    <input type='date' ng-model='myDate'>

   myApp.controller('myCtrl',['$scope','$filter'],
   function ($scope,$filter)
   {
    //consider this string comes from api...
   var stringDate='20/11/2016';
   var convertedDate=new Date(stringDate);
   $scope.myDate=$filter('date')(convertedDate,'MM/dd/yyyy');
   });
var stringDate1=this.dStartDate;
var splitDate1 = stringDate1.split('-');
var year1  = splitDate1[0];
var month1 = splitDate1[1];
var day1 = splitDate1[2];
this.dStartDate = month1+"-"+day1+"-"+year1;
console.log("date"+this.dStartDate);

Using momentjs 使用moment.js

var convertedDate = moment('20/11/2016', 'dd/MM/yyyy');

Using vanilla javascript 使用香草JavaScript

var dateArray = '20/11/2016'.split('/');
var convertedDate = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2]);

Probably this is not the best implementation, but it works! 可能这不是最好的实现,但可以!

remove 'new' so 删除“新”,所以

var stringDate='20/11/2016';
var convertedDate=new Date(stringDate);

should be 应该

var stringDate='20/11/2016';
var convertedDate=Date(stringDate);

First of all you can not give stringDate directly as input to Date object as it is not a valid Date string. 首先,您不能将stringDate直接作为Date对象的输入,因为它不是有效的Date字符串。

Revised code: 修改后的代码:

var stringDate='20/11/2016';
var splitDate = stringDate.split('/');
var convertedDate=new Date(splitDate[2], splitDate[1]-1, splitDate[0]);
console.log(convertedDate.toLocaleDateString("en-US"));
$scope.myDate = convertedDate.toLocaleDateString("en-US");

Here using en-US locale returns 11/20/2016 format. 在这里使用en-US语言环境将返回11/20/2016格式。 You can find more about toLocale conversion here . 您可以在此处找到有关toLocale转换的更多信息。

Here you go: 干得好:

  var stringDate='20/11/2016';
  $scope.myDate=$filter('date')(stringDate, 'MM/dd/yyyy');

You can split and then pass to date object. 您可以拆分然后传递给日期对象。 After that using Date functions reform the date. 之后,使用Date函数重新设置日期。

var dateArray = '31/12/2016'.split('/');
var convertedDate = new Date(dateArray[1]+'-'+dateArray[0]+' '+dateArray[2]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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