问题
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