简体   繁体   English

如何在Angular-JS中获取日期格式

[英]How to get date format in Angular-JS

My requirement is something different. 我的要求是不同的。 I want to get the date format, not to format the date. 我想获取日期格式,而不是格式化日期。 Means I have a date string and now I want to get the date format of that date and apply it to the another date as a format. 意味着我有一个日期字符串,现在我想获取该日期的日期格式并将其作为格式应用到另一个日期。

Let me explain in brief with example: 让我用例子简单地解释一下:

var dateStr = "2015-06-06T12:00:00Z";
var d = new Date(dateStr);

here my date format is yyyy-MM-ddTHH:mm:ssZ you can see in dateStr object. 在这里,我的日期格式是yyyy-MM-ddTHH:mm:ssZ ,可以在dateStr对象中看到。

Now i will create another date and want to apply the same date-format to this new date. 现在,我将创建另一个日期,并希望将相同的日期格式应用于此新日期。

var formatStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // want to get this from above date, not hard coded like this.
var newDate = $filter('date')(d, formatStr);

here you can see that i have hard coded the format string, which i don't want to do. 在这里您可以看到我已经对格式字符串进行了硬编码,这是我不想做的。 Here this string should be come from the above d date/or dateStr String. 这里的字符串应该来自上面的d date /或dateStr字符串。

As @Rob said, there is doubt on the reliably for all formats. 正如@Rob所说,对于所有格式的可靠性都存在疑问。 What you need is pre defined map with key being the format and value being its corresponding regular expression. 您需要的是预定义的映射,键为格式,值为相应的正则表达式。

Now, create a function with input as dateStr and will return the format. 现在,创建一个输入为dateStr的函数,并将返回格式。 Like 喜欢

function getDateFormat(dateStr) {
 var format = default_format;
 // Check in map for format
 // If you get the format in map, return that else return a default format.
 return format;
} 

You can do it by using momment.js 您可以使用momment.js做到这一点

http://momentjs.com/downloads/moment.js http://momentjs.com/downloads/moment.js

  van date=new Date(date);
  var dateInFormate=moment(date);
  var date=dateInFormate.format('yyyy-MM-ddTHH:mm:ssZ'); 

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

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