yym-yumeng123 / Interview

学习中的一些问题
3 stars 1 forks source link

Date #45

Open yym-yumeng123 opened 7 years ago

yym-yumeng123 commented 7 years ago

1、 写一个函数getChIntv,获取从当前时间到指定日期的间隔时间

var str = getChIntv("2017-02-08");
console.log(str);  // 距除夕还有 20 天 15 小时 20 分 10 秒
function getChIntv(date){
  var now = Date.now()
  var specifiedDate = Date.parse(date)
  var differ = Math.abs(now - specifiedDate)
  var totalSeconds = Math.floor(differ / 1000);
      //获取秒
      seconds = totalSeconds%60,
      totalMinutes = Math.floor(totalSeconds / 60),
     //获取分钟
      minutes = totalMinutes % 60,
      totalHours = Math.floor(totalMinutes / 60),
      hours = totalHours % 24,
      totalDays =  Math.floor(totalHours / 24),
      days = totalDays % 365,
      totalYears = Math.floor(totalDays / 365);
   var differTime = totalYears + '年' + days + '天' + hours + '小时' + minutes + '分钟' + seconds + '秒';
    return differTime;
}
var str = getChIntv("2017-03-08 10:30:24");
console.log(str);  //"0年179天11小时23分钟59秒"

2、把hh-mm-dd格式数字日期改成中文日期

var str = getChsDate('2015-01-08');
console.log(str);  // 二零一五年一月八日
function getChsDate(str) {
    var dist = ["零","一","二","三","四","五","六","七","八","九","十","十一","十二","十三","十四","十五","十六","十七","十八","十九","二十","二十一","二十二","二十三","二十四","二十五","二十六","二十七","二十八","二十九","三十","三十一"];
    var arr = str.split('-');
    var year = arr[0];
    var month = arr[1];
    var day = arr[2];

    var Chyear = dist[parseInt(year[0])] + dist[parseInt(year[1])] + dist[parseInt(year[2])] +dist[parseInt(year[3])] + '年';
var Chmonth = dist[parseInt(month)] + '月';
var Chday = dist[parseInt(day)] + '日';
return Chyear + Chmonth + Chday ;
}
var str = getChsDate('2015-01-08');
console.log(str);  // 二零一五年一月八日

8、写一个函数,参数为时间对象毫秒数的字符串格式,返回值为字符串。假设参数为时间对象毫秒数t,根据t的时间分别返回如下字符串:

yym-yumeng123 commented 7 years ago

第八题写错了.更正如下

function getFriendlyDate(timeStr){
  var interval = Date.now() - parseInt(timeStr)
  var ch = interval > 0 ? '前': '后'
  var str
  interval = Math.abs(interval)
  switch (true){
    case interval < 60*1000:
      str = '刚刚'
      break
    case interval < 60*60*1000:
      str = Math.floor(interval/(60*1000)) + '分钟' + ch
      break
    case interval < 24*60*60*1000:
      str = Math.floor(interval/(60*60*1000)) + '小时' + ch
      break
    case interval < 30*24*60*60*1000:
      str = Math.floor(interval/(24*60*60*1000)) + '天' + ch
      break
    case interval < 12*30*24*60*60*1000:
      str = Math.floor(interval/(30*24*60*60*1000)) + '个月' + ch
      break    
    default:  
      str = Math.floor(interval/(12*30*24*60*60*1000)) + '年' + ch
  }
  return str
}
console.log( getFriendlyDate('1505122360640') )  //"7分钟前"
console.log( getFriendlyDate('1503122360640') )  //"23天前"
console.log( getFriendlyDate('1203122360640') )  //"9年前"
console.log( getFriendlyDate('1508122360640') )  //"1个月后"