zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    iOS开发系列--通知与消息机制(转)
    iOS Storyboard全解析(转)
    在IOS代码中使用UNIX命令
    如何用代码实现iPhone手机软件注销和手机重启
    ios多线程开发 GCD常见用法
    ios多线程开发 GCD的基本使用
    ios错误码:NSError对象.code
    iOS9 HTTP请求失败
    (转)空指针和野指针
    (转)ARC指南
  • 原文地址:https://www.cnblogs.com/xihe/p/6138616.html
Copyright © 2011-2022 走看看