發布於 2023-02-16

更新於 2023-02-16

程式

約413字 (3分鐘閱讀)

Nuxt3 x TypeScript x 輸入年月日只取年份

Title Image

前言 - Prologue

當我們在開發 Web 時,經常需要從用戶輸入的資料中提取特定的數據,例如日期。在某些情況下,我們可能只需要從日期中提取年份,而不需要包括月份和日期。這時使用 Nuxt3 和 TypeScript 也可以簡單地實現這個功能,提高開發效率。在本篇教學中,將介紹如何從日期中提取年份的具體實現過程。

正文 - Main text

以下是一個以 Nuxt3 寫的 TypeScript 函式:

function getYearFromDate(dateString: string): number | null {
  // 使用 JavaScript 內建的 Date 物件將字串轉換為日期
  const date = new Date(dateString);
  // 使用 getFullYear() 取得日期的年份
  const year = date.getFullYear();
  // 如果該字串無法轉換為日期,會返回 null
  return isNaN(year) ? null : year;
}

這個函式會接收一個字串,然後使用 JavaScript 內建的 Date 物件將這個字串轉換為日期。接著我們可以使用 getFullYear() 方法來取得該日期的年份。如果該日期字串無法轉換為日期,getYearFromDate() 會返回 null。

取用函式範例:

const dateString = '2022-08-15';
const year = getYearFromDate(dateString);
console.log(year);
// Expected output: 2022

請注意:此範例函式假設輸入的字串只符合格式 yyyy-mm-dd,其餘格式可能會導致不正確的結果或錯誤。如果需要處理其他格式的日期字串,您可以參考 JavaScript 的 Date 物件文檔,或使用第三方日期處理庫。

Reference implementation

因為有用到,想說紀錄一下所以才有這第二篇文 ...?!

#5 串接 TMDB API 的電影清單搜尋實作

Nuxt3 x TypeScript x 輸入年月日只取年份

https:///blog/14

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.