使用豆包 MarsCode如何丝滑的实现`多时区日期实时显示`?

435 阅读3分钟

快来使用豆包 MarsCode来和我一起实现吧!

业务场景

最近在一个项目的开发中,产品想要实现一个多时区日期实时展示的效果,乍一看可能觉得有点复杂,没啥思路,那么接下来,我就带领大家使用豆包MarsCode来快速实现。

image.png

实现

安装插件MarsCode

在vscode中安装MarsCode,安装成功后在最左侧会有个图标,点击进去就可使用了。

image.png

思路

1、在输入框输入你想查询的内容

image.png

2、我们先输入“封装一个获取不同时区的当前时间以及和北京时间的差值。”

image.png

立即得到完整的功能函数:

  • getCurrentTimeByTimeZone 获取当前时间
  • getTimeDifferenceWithBeijing 获取目标时区与北京时间的差值

3、我们想要实时显示,可以输入“实时获取当前时间并显示”

image.png

4、我们还需要显示当前的星期,可搜索“获取当前时间的星期”

image.png

5、当前为北京时区时,还需要获取距离北京时间日落的差值,可搜索“获取当前时间距离北京落日时间的差值”

image.png

跟着搜索,我们已经基本梳理清楚了这个业务场景实现的思路。

代码实现

第一步、根绝UI设计稿,编写DOM和CSS

<template>
  <div class="box-wrapper">
    <div
      class="box"
      v-for="item in cityData"
      :class="item.timezone > 0 ? 'white' : 'night'"
    >
      <div class="city-title">{{ item.name }}</div>
      <div class="city-time">
        <span>{{ item.time.split(":")[0] }}</span> :
        <span>{{ item.time.split(":")[1] }}</span> :
        <span>{{ item.time.split(":")[2] }}</span>
      </div>
      <div class="city-date">{{ item.date }}</div>
      <div class="city-diff" v-if="item.isBeijing">{{ item.sunDay }}</div>
      <div class="city-diff" v-else>
        比中国北京{{ item.timezone > 0 ? "快" : "慢" }}{{ item.diff }}小时
      </div>
    </div>
  </div>
</template>

<style>
.box-wrapper {
  display: flex;
  gap: 16px;
  padding: 20px;
  color: #fff;
}

.box {
  width: 280px;
  min-height: 177px;
  background-size: 100% 100%;
  border-radius: 8px;
  padding: 12px;
}

.white {
  background: url(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b3eede2c32f24b6ca0cae1127b43c4a0~tplv-k3u1fbpfcp-watermark.image?)
    no-repeat center;
}

.night {
  background: url(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5ac280ee4b6842218c80e48b8078659a~tplv-k3u1fbpfcp-watermark.image?)
    no-repeat center;
}

.city-title {
  font-size: 14px;
}

.city-date {
  width: 158px;
  padding: 3px 12px;
  background: rgba(0, 47, 124, 0.3);
  border-radius: 4px;
  margin: 18px auto;
}

.city-diff {
  text-align: center;
}

.city-time {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 12px;
  font-size: 32px;
}

.city-time span {
  min-width: 50px;
  padding: 6px 0;
  background: rgba(206, 222, 255, 0.2);
  border-radius: 5px;
  line-height: 52px;
  text-align: center;
}
</style>

第二步、根据梳理出的思路,编写功能代码

1、5个时区的数据准备

<script setup>
  import { ref, onMounted } from 'vue';
  // 需要展示的五个时区
  const cityData = ref([{
      name: '中国北京时间 UTC+8',
      timezone: 8,
      date: '',
      time: '',
      diff: '',
      isBeijing: true,
      sunDay: ''
    },
    {
      name: '越南河内时间 UTC+7',
      timezone: 7,
      date: '',
      time: '',
      diff: ''
    },
    {
      name: '波兰华沙时间 UTC+2 夏令时',
      timezone: 2,
      date: '',
      time: '',
      diff: ''
    },
    {
      name: '美国休斯顿时间 UTC-5 夏令时',
      timezone: -5,
      date: '',
      time: '',
      diff: ''
    },
    {
      name: '墨西哥墨西哥城时间 UTC-6',
      timezone: -6,
      date: '',
      time: '',
      diff: ''
    }]);
</script>

2、一些公共方法

    // 获取该时区当前时间
    const getCurrentTimeByTimeZone = (timezone) => {
      const now = new Date();
      const offset = now.getTimezoneOffset(); // 获取本地时间与 UTC 时间的分钟差
      const targetTime = now.getTime() + (offset + timezone * 60) * 60000; // 计算目标时区的时间
      return new Date(targetTime);
    };

    // 获取目标时区与北京时间的差值
    const getTimeDifferenceWithBeijing = (timezone) => {
      const beijingTime = getCurrentTimeByTimeZone(8); // 获取北京时间
      const targetTime = getCurrentTimeByTimeZone(timezone); // 获取目标时区时间
      const difference = beijingTime.getTime() - targetTime.getTime(); // 计算时间差
      const hours = Math.floor(difference / (1000 * 60 * 60)); // 转换为小时
      return hours;
    };

    // 时间格式化
    const formatTime = (date, fmt) => {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          const str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)? str : padLeftZero(str));
        }
      }
      return fmt;
    };

    // 获取当前的星期
    const getWeekDay = (date) => {
      const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const dayOfWeek = date.getDay();
      return daysOfWeek[dayOfWeek];
    }

    // 获取北京当天时间距离日落19:11的时间
    const getSunTime = (sunhours,sunminutes) => {
      // 获取当前时间
      let now = new Date();

      // 获取今天的落日时间
      let sunsetTime = getSunsetTime(new Date(now.getFullYear(), now.getMonth(), now.getDate()),sunhours,sunminutes);

      // 计算差值(以毫秒为单位)
      let difference = sunsetTime - now;

      // 将差值转换为小时和分钟
      let hours = Math.floor(difference / (1000 * 60 * 60));
      let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));

      return `距离北京落日${sunhours}:${sunminutes}还有${hours}小时${minutes}分钟`
    }

    // 假设我们有一个getSunsetTime函数可以获取北京当天的落日时间(以毫秒为单位)
    const getSunsetTime = (date,sunhours,sunminutes) => {
        // 这里需要一个API或数据源来提供具体的落日时间
        // 例如,我们可以使用一个假的落日时间来测试
        return date.setHours(sunhours,sunminutes, 0);
    }

    // 时间补零
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length);
    }; 

一些功能函数写好后,自己不想写注释,可以使用MarsCode一键生成注释。

如:选中想要注释的函数,在左侧的输入框中输入/选择注释,一键回车就生成注释了。

image.png

3、实时展示

   onMounted(() => {
      setInterval(() => {
        formatCityData();
      }, 1000);
    })

    const formatCityData = () => {
      cityData.value.forEach(item => {
        let newDate = getCurrentTimeByTimeZone(item.timezone)
        let diff = getTimeDifferenceWithBeijing(item.timezone);
        item.date = `${formatTime(newDate, 'yyyy-MM-dd')} ${getWeekDay(newDate)}`;
        item.time = formatTime(newDate, 'hh:mm:ss')
        item.diff = diff
        item.sunDay = item.isBeijing ? getSunTime(19,11) : ''
      })
    }

我们也可以给formatCityData一键生成注释

image.png

效果

作者有话说

MarsCode真的蛮好用的,搜索问题的速度很快,今后在编码时应该会常用。