Codewars-Javascript训练手册:Date 对象
乌龟赛跑问题(Tortoise racing)
两只蠢蠢的乌龟长跑比赛,年老的乌龟(老龟)跑的慢v1,领先跑了一段距离g,年青的乌龟(青龟)跑得快v2,在某个时间点后够追上老龟,那么问题来了:什么时间后青龟追上老龟。
Examples:
race(720, 850, 70) => [0, 32, 18]
race(80, 91, 37) => [3, 21, 49]
写出实现这个功能的函数。
Solution:
function race(v1, v2, g) {
if(v1>v2){
return null;
}else{
var t = g/(v2-v1)*60*60*1000;
var dt = new Date(t);
return [dt.getHours(),dt.getMinutes(),dt.getSeconds()];
}
}
知识点: 格式化时间,先转化时间为毫秒单位,然后使用语法new Date(milliseconds)
获取Date对象 ,获取到的日期时间1970/01/01 00:00:00
为起点开始计算的,起点的时分秒还要加上当前所在的时区,北京时间的时区为东8区,起点时间实际为:1970/01/01 08:00:00
var t = 70/130*3600000;//转化为毫秒单位显示
var dt = new Date(t);
var hours = dt.getHours();
console.log(hours);//输出为8,实际应为0,中国时区的问题。
console.log(hours-8);//所以是国内网站应该减去8
var minutes = dt.getMinutes();
console.log(minutes);//获取分钟
var seconds = dt.getSeconds()
console.log(seconds);//获取秒数
Date对象的getHours(),getMinutes()和getSeconds()函数获取相应单位的时间。
The Coupon Code(优惠码)
Write a function called checkCoupon to verify that a coupon is valid and not expired. If the coupon is good, return true. Otherwise, return false.(写一个函数checkCoupon 用来验证优惠码是有效的且未过期的,如果优惠码可用,返回true,否则返回false)
A coupon expires at the END of the expiration date. All dates will be passed in as strings in this format: “June 15, 2014”(expiration date的格式如:June 15, 2014)
Solution:
function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){
return (enteredCode===correctCode && new Date(currentDate)<= new Date(expirationDate));
}
知识点: 输入一个时间的字符串并将之格式化,有两种方法:一、通过new Date()
;二、通过Date对象的静态方法Date.parse().例:
var datestr = 'June 15, 2014';
console.log(new Date(datestr));
//输出: Date {Sun Jun 15 2014 00:00:00 GMT+0800}
console.log(Date.parse(datestr));
//输出: 1402761600000
Date.parse(dateStr):把字符串转换为 Date 对象 ,然后返回此 Date 对象与1970/01/01 00:00:00
之间的毫秒值(北京时间的时区为东8区,起点时间实际为:1970/01/01 08:00:00
) 。可以通过这两种方式比较两个时间字符串的大小。
Codewars得票最高的答案:
function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){
return enteredCode === correctCode && Date.parse(expirationDate) >= Date.parse(currentDate)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现