(vue) vue プロジェクトの日付時刻週の取得

(vue) vue プロジェクトの日付時刻週の取得


効果:
ここに画像の説明を挿入

コード:

<div class="top-time">
  <div class="time-currentDate">
    {
    
    {
    
     currentDate }}
    <div class="time-img">
      <img src="@/assets/image/icon-time.png" alt />
    </div>
  </div>
  <div class="time-Weekday">
    <span>{
    
    {
    
     currentWeekday }}</span>
    <span>{
    
    {
    
     currentTime }}</span>
  </div>
</div>

js

data() {
    
    
  return {
    
    
    currentDate: "",
    currentTime: "",
    currentWeekday: "",
  }  
},

created() {
    
    
  setInterval(() => {
    
     
    this.getCurrentDateTime();
    this.getCurrentWeekday();
  }, 1000);
},   

methods: {
    
    
  getCurrentDateTime() {
    
    
    const now = new Date();
    this.currentDate = now.toLocaleDateString();
    // this.currentTime = now.toLocaleTimeString(); // 时分秒格式
    this.currentTime = now.toLocaleTimeString([], {
    
    
      hour: "2-digit",
      minute: "2-digit",
    }); //时分格式
  },
  getCurrentWeekday() {
    
    
    const weekdays = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    const now = new Date();
    this.currentWeekday = weekdays[now.getDay()];
  },  
}

上記コードでは、
1.作成したフック関数でコンポーネント作成時にgetCurrentDateTimeメソッドとgetCurrentWeekdayメソッドを呼び出し、取得した日付、時刻、週をdata属性に保存します。
2. 次に、補間式 { {}} を使用してテンプレート内の データを表示します。

getCurrentDateTime メソッドは、toLocaleDateString メソッドと toLocaleTimeString メソッドを使用して、ローカライズされた日付と時刻の文字列を取得します。
getCurrentWeekday メソッドは、getDay メソッドを使用して現在の日付に対応する週のインデックスを取得し、インデックスから対応する週のテキストを取得します。

  • 時間形式

上記のコードでは、
1. toLocaleTimeString メソッドの 2 番目のパラメーターを空の配列 [] に設定します。2
. 次に、空の配列 {hour: '2-digit', minutes: '2 -digit'} 内のオプション オブジェクトを渡します。 。
このオプション オブジェクトは、時間と分の表示形式を指定します。「2 桁」は、数値を 2 桁で表示することを意味します。このような設定では、生成される時刻文字列に秒は含まれません。

おすすめ

転載: blog.csdn.net/qq_44754635/article/details/131891625