Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【面经】字节跳动 笔试2:格式化发布时间 #2

Open
liam61 opened this issue Mar 17, 2019 · 0 comments
Open

【面经】字节跳动 笔试2:格式化发布时间 #2

liam61 opened this issue Mar 17, 2019 · 0 comments
Labels
面经 面经

Comments

@liam61
Copy link
Owner

liam61 commented Mar 17, 2019

格式化发布时间

找准每段时间的变换点即可

function format(date, testMode) {
  const MIN = 60 * 1000;
  const HOUR = 60 * MIN;
  const DAY = HOUR * 24;
  const WEEK = DAY * 7;
  const time = testMode ? date : Date.now() - date;

  if (time < MIN) return '刚刚';

  if (time < HOUR) return Math.floor(time / MIN) + '分前';

  if (time < DAY) return Math.floor(time / HOUR) + '小时前';

  if (time < WEEK) return Math.floor(time / DAY) + '天前';

  return new Date(testMode ? Date.now() - date : date).toLocaleString();
}

// 测试
console.log(format(60 * 1000 - 1, true)); // 59 秒 999
console.log(format(60 * 1000, true)); // 1 分

console.log(format(60 * 1000 * 59 + 59 * 1000 + 999, true)); // 59 分 59 秒 999
console.log(format(60 * 1000 * 60, true)); // 1 小时

console.log(format(60 * 1000 * 60 * 23 + 60 * 1000 * 59 + 59 * 1000 + 999, true)); // 23 小时 59 分 59 秒 999
console.log(format(60 * 1000 * 60 * 24, true)); // 1 天

console.log(format(60 * 1000 * 60 * 24 * 6, true)); // 6 天
console.log(format(60 * 1000 * 60 * 24 * 7, true)); // 7 天

// 正常使用
console.log(format(1554111847534)); // 发布时的时间戳
@liam61 liam61 added the 面经 面经 label Mar 17, 2019
@liam61 liam61 changed the title 【面经】字节跳动 笔试4:格式化数字。正则和非正则实现 【面经】字节跳动 笔试2:格式化发布时间 Mar 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
面经 面经
Projects
None yet
Development

No branches or pull requests

1 participant