Subtracting hours from date string

一曲冷凌霜 提交于 2019-12-25 16:56:07

问题


I am working in node js and by using moment-timezone package I have generated a date:

2017-4-10 19:04:47

Below is the code I used to generate this date time which is for timezone Asia/shanghai:

var momentTimezone = require('moment-timezone');
console.log(momentTimezone(new Date()).tz('Asia/shanghai').format('Y-M-D HH:MM:ss'));

Now I want to subtract hours from this time to generate another date. I want to subtract 9940 hours.

I have searched for many hours but could not find exact solution.

Below is the python code which I have to replicate:

 end_time = datetime.now(g.china) 
 //g.china =   timezone("Asia/Shanghai")
 begin_time = end_time - timedelta(hours=9940)

Any guidance over this would be highly appreciated.

Thanks!


回答1:


You can simply use moment subtract method.

Here a working sample:

// Current time in Shanghai
var m = moment.tz('Asia/Shanghai');
console.log(m.format('Y-M-D HH:mm:ss'));
// Subtract 9940 hours
console.log(m.subtract(9940, 'hours').format('Y-M-D HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>

Note that you should use lowercase mm to show minutes because uppercase MM represents months. See format tokens.



来源:https://stackoverflow.com/questions/43322526/subtracting-hours-from-date-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!