国际化日期(inti)

我们可以使用国际化API自动的格式化数字或者日期,并且格式化日期或数字的时候是按照各个国家的习惯来进行格式化的,非常的简单;

const now = new Date();
labelDate.textContent = new Intl.DateTimeFormat('zh-CN').format(now);

在这里插入图片描述

比如说这是按照中国的习惯来进行格式化,我们习惯按照年月日时分秒来排列时间

● 但是这样格式化的话只能出现年月日,时间却没有了

const now = new Date();
const options = {
  hour: 'numeric',
  minute: 'numeric',
  day: 'numeric',
  month: 'numeric',
  year: 'numeric',
  weekday: 'long',
};
labelDate.textContent = new Intl.DateTimeFormat('zh-CN', options).format(now);

在这里插入图片描述

● 我们也可以直在浏览器中自动的获取你的地区,无需手动的去指定地区

const now = new Date();
const options = {
  hour: 'numeric',
  minute: 'numeric',
  day: 'numeric',
  month: 'numeric',
  year: 'numeric',
  weekday: 'long',
};

const lacale = navigator.language;
console.log(lacale);

labelDate.textContent = new Intl.DateTimeFormat(lacale, options).format(now);

在这里插入图片描述

● 再次回到我们的应用程序,我们给每个用户中定义了国家码,要实现每个人登录按照他国家的习惯来显示时间
在这里插入图片描述

const now = new Date();
const options = {
  hour: 'numeric',
  minute: 'numeric',
  day: 'numeric',
  month: 'numeric',
  year: 'numeric',
};
labelDate.textContent = new Intl.DateTimeFormat(
  currentAccount.locale,
  options
).format(now);

在这里插入图片描述
在这里插入图片描述

● 除了这些,存取款的时间也需要根据用户国家改变

const formatMovementDate = function (date, locale) {
  const calcDaysPassed = (date1, date2) =>
    Math.round(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));

  const daysPassed = calcDaysPassed(new Date(), date);

  if (daysPassed === 0) return '今天';
  if (daysPassed === 1) return '昨天';
  if (daysPassed <= 7) return `${daysPassed} 天前`;

  return new Intl.DateTimeFormat(locale).format(date);

  // const day = `${date.getDate()}`.padStart(2, 0);
  // const month = `${date.getMonth() + 1}`.padStart(2, 0);
  // const year = date.getFullYear();
  // return `${day}/${month}/${year}`;
};

const displayMovements = function (acc, sort = false) {
  containerMovements.innerHTML = '';

  const movs = sort
    ? acc.movements.slice().sort((a, b) => a - b)
    : acc.movements;

  movs.forEach(function (mov, i) {
    const type = mov > 0 ? 'deposit' : 'withdrawal';
    const date = new Date(acc.movementsDates[i]);
    const displayDate = formatMovementDate(date, acc.locale);

    const html = `
      <div class="movements__row">
        <div class="movements__type movements__type--${type}">${
      i + 1
    } ${type}</div>
        <div class="movements__date">${displayDate}</div>
        <div class="movements__value">${mov.toFixed(2)}€</div>
      </div>
    `;

    containerMovements.insertAdjacentHTML('afterbegin', html);
  });
};

在这里插入图片描述

大家也可以根据下面的文档详细的学习这个国际化API
INIT

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值