【发布时间】:2021-06-05 14:11:48
【问题描述】:
const seconds = 1000000
var now = moment(moment.duration(seconds).asSeconds()).format('Y[y],M[m],D[d],H[h]')
我想将此秒格式化为年、月、日、小时、分钟,所以我无法找到我出错的地方如何在 React 本机中获得这种格式
【问题讨论】:
标签: react-native momentjs
const seconds = 1000000
var now = moment(moment.duration(seconds).asSeconds()).format('Y[y],M[m],D[d],H[h]')
我想将此秒格式化为年、月、日、小时、分钟,所以我无法找到我出错的地方如何在 React 本机中获得这种格式
【问题讨论】:
标签: react-native momentjs
此代码可能对您有所帮助
export function formatDate(seconds) {
var d = new Date(seconds*1000),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [day,month,year].join('/');
}
此代码将返回 dd/mm/yyyy。如果你想返回日期+时间,那么你只需返回
export function formatDate(seconds) {
var d = new Date(seconds*1000)
return d.toLocaleString()
}
如果您想获取剩余时间、日期、月份和年份,那么您应该使用此代码
function secondsToHms(sec) {
sec = Number(sec);
var y = Math.floor(sec/31536000) //<<years
var w= Math.floor(y*31536000)
var w1=Math.floor(w-sec)
w=Math.floor(Math.abs(w1)/604800)//<<weeks
var d=Math.floor(Math.abs(w)*604800)
var d1=Math.floor(Math.abs(d)-Math.abs(w1))
d=Math.floor(Math.abs(d1)/86400)
d=Math.abs(d) //<<day
var h = Math.floor(d*86400);
h=Math.floor(h-Math.abs(d1))
h=Math.floor(Math.abs(h)/3600)//<<hours
var m = Math.floor(sec % 3600 / 60);//<<minutes
var s = Math.floor(sec % 3600 % 60);//<<seconds
var yDisplay = y > 0 ? y + (y == 1 ? " year, " : " years, ") : "0 year, ";
var wDisplay = w > 0 ? w + (w == 1 ? " week, " : " weeks, ") : "0 week, ";
var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "0 day, ";
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "0 hour, ";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "0 minute, ";
var sDisplay = s > 0 ? s + (s == 1 ? " second. " : " seconds. ") : "0 second. ";
return yDisplay + wDisplay + dDisplay + hDisplay + mDisplay + sDisplay;
}
console.log(secondsToHms(1000000))
【讨论】: