1日期格式化
script type="text/javascript">
// 模拟一个朋友圈
// Date.parse("2022-8-1 12:35:09")
// 获取到当前时间
var now = new Date()
// 获取发布朋友圈的时间
var fbtime = new Date("2022-8-2 12:35:09")
// 转换成毫秒
now = Date.parse(now)
fbtime = Date.parse(fbtime)
// console.log(now)
// console.log(fbtime)
// 计算时间差
var time = now - fbtime
// 转换成秒
var secondTime = parseInt(time / 1000)
// 转换成分钟
var minutesTime = parseInt(time / 1000 / 60)
// 转换小时
var hoursTime = parseInt(time / 1000 / 60 / 60)
// 转换成天数
var daysTime = parseInt(time / 1000 / 60 / 60 / 24)
console.log(secondTime)
console.log(minutesTime)
console.log(hoursTime)
console.log(daysTime)
// 分支结构判断,根据不同的情况输出不同的结果
if (daysTime >= 1) {
console.log(daysTime + "天以前")
} else if (hoursTime > 0 && hoursTime < 24) {
console.log(hoursTime + "小时以前")
} else if (minutesTime > 0 && minutesTime < 60) {
console.log(minutesTime + "分钟以前")
} else if (secondTime > 0 && secondTime < 60) {
console.log(secondTime + "秒以前")
}
</script>
1 获取到当前时间
var now = new Date()
2 // 获取发布朋友圈的时间
var fbtime = new Date("xxxx-xx-xx 12:35:09")
3 计算时间差
var time = now - fbtime
![]()

<script type="text/javascript">
var cont = 5
var timer = setInterval(function() {
if (cont > 0) {
console.log(cont)
cont--
} else {
clearInterval(timer)
}
}, 1000)
var str = "Hello World"
//[2,4):从开始位置截取,到指定位置结束,但取不到结束位置的字符
console.log(str.substring(2, 4))
//从开始位置进行截取,截取指定长度的字符串
console.log(str.substr(2, 5))
//concat()
console.log(str.concat("aaa"))
//slice()
console.log(str.slice(1, 3))
//indexOf()返回的是-一个字符的第- -个索引值, 还可以用于判断某个字符是否存在
//字符串中
console.log(str.indexOf("1"))
//要将str中的1全部替换成*
//replace():替换的是满足条件的第一个出现字符
var str = "Hello World"
</script>
本文介绍了如何使用JavaScript进行日期格式化和计算时间差。首先通过`new Date()`获取当前时间,然后设置一个特定日期如"xxxx-xx-xx 12:35:09"作为参考时间。接着,通过相减操作得到两个日期间的时间差。
346

被折叠的 条评论
为什么被折叠?



