[英]Javascript Invalid Date to string format
I'm trying to parse time which is retrieved from MySql via jSon 我正在尝试解析通过jSon从MySql检索的时间
something like: 就像是:
new Date('12:15:24').toString('h:mmtt');
but I keep getting Invalid Date in console 但我在控制台中不断收到无效日期
What I need to do is convert 24 hour format into 12 hour am/pm and vice versa 我需要做的是将24小时格式转换为上午12点,反之亦然
The Date()
constructor only likes a very restricted set of date formats. Date()
构造函数仅喜欢一组非常受限制的日期格式。 If your input format is fixed at 'hh:mm:ss'
it is probably easier to format it using a simple string replace: 如果您的输入格式固定为
'hh:mm:ss'
,则使用简单的字符串替换来设置其格式可能会更容易:
function formatTime(time) { return time.replace(/(\\d?\\d)(:\\d\\d):(\\d\\d)/, function(_, h, m) { return (h > 12 ? h-12 : +h === 0 ? "12" : +h) + m + (h >= 12 ? "pm" : "am"); }); } console.log( formatTime('00:15:24') ); console.log( formatTime('09:15:24') ); console.log( formatTime('10:15:24') ); console.log( formatTime('11:15:24') ); console.log( formatTime('12:15:24') ); console.log( formatTime('13:15:24') ); console.log( formatTime('14:15:24') );
Further reading: 进一步阅读:
I would consider using date/time manipulation library, such as http://momentjs.com/ . 我会考虑使用日期/时间操作库,例如http://momentjs.com/ 。
You can also achieve what you want by splitting the time string and creating a Date() object. 您还可以通过拆分时间字符串并创建Date()对象来实现所需的功能。 Example:
例:
var time = '12:15:24';
var timePortions = time.split(':');
new Date(0,0,0,timePortions[0], timePortions[1], timePortions[2])
This is not a safe way to manipulate date/time, though. 但是,这不是操作日期/时间的安全方法。
it is better to use moment.js to handle datetime like this 最好使用moment.js这样处理日期时间
// get hours:minutes:seconds of the date 31-Jan_2016 9.31.21 console.log(moment('2016-01-31 09:30:21').format('HH:mm:ss')) // get current hours:minutes:seconds console.log(moment().format('HH:mm:ss')) // get current date-month-year hours:minutes:seconds console.log(moment('2016-01-31 09:30:21').format('DD-MM-YYYY HH:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.