javascript用户值转换为格式 [英] javascript user value convert to format

查看:95
本文介绍了javascript用户值转换为格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    var t = "Jan. 20, 2017 20:28:53"
    var s = t.format("%m/%d/%Y %H:%M:%S");
    alert(s);

如何将值转换为


2017年1月20日20:28:53

01/20/2017 20:28:53

这种格式。请帮助我。谢谢...

this format.Please help me. Thank you...

推荐答案

使用Date构造函数解析字符串(或Date.parse,它们等效于解析)不是由于实现之间存在许多差异,因此推荐使用。解析格式为'Jan的字符串。 20,2017 20:28:53'取决于实现,并且可能导致无效的日期。

Parsing strings with the Date constructor (or Date.parse, they are equivalent for parsing) is not recommended due to the many differences between implementations. Parsing of a string in a format like 'Jan. 20, 2017 20:28:53' is implementation dependent and may result in an invalid date.

如果您要通过字符串创建日期,请使用定制功能

If you want to create a Date from a string, use a bespoke function or a library, there are plenty to choose from.

但是您不需要创建Date来重新格式化日期字符串,只需重新格式化字符串即可:

But you don't need to create a Date to reformat a date string, you can just reformat the string:

function reformatDatestring(s) {
  function z(n) {return (n<10?'0':'') + n}
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  var b = s.split(/[\.,]?\s/);
  var month = months.indexOf(b[0].toLowerCase());
  return z(month+1) + '/' + z(b[1]) + '/' + b[2] + ' ' + b[3];
}

console.log(reformatDatestring('Jan. 20, 2017 20:28:53'));

这篇关于javascript用户值转换为格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆