Skip to content

1.YYYY-MM-DD HH:MM:SS格式,js函数

你可以创建一个JavaScript函数来将日期对象格式化为 "YYYY-MM-DD HH:MM:SS" 格式。下面是一个示例函数:

js
function formatDateToYYYYMMDDHHMMSS(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 示例用法
const currentDate = new Date();
const formattedDate = formatDateToYYYYMMDDHHMMSS(currentDate);
console.log(formattedDate); // 输出: "2023-09-18 15:24:30"

这个函数接受一个Date对象作为参数,并将其格式化为 "YYYY-MM-DD HH:MM:SS" 格式。我们使用getYear(), getMonth(), getDate(), getHours(), getMinutes(), 和 getSeconds() 方法来获取相应的时间部分,并使用 padStart() 方法确保单个数字的部分(如月、日、时、分、秒)始终有两位数。最后,我们将这些部分组合成所需的格式。

注意:date一开始是一个时间戳!

2.ts形式

ts
const dateFormat: (date: Date) => string = (date) => {
  const year: string = String(date.getFullYear());
  const month: string = String(date.getMonth() + 1).padStart(2, "0"); // Months are zero-based
  const day: string = String(date.getDate()).padStart(2, "0");
  const hours: string = String(date.getHours()).padStart(2, "0");
  const minutes: string = String(date.getMinutes()).padStart(2, "0");
  const seconds: string = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

3.泛型形式

ts
const dateFormat = <T extends Date | number>(date: T): string => {
  const parsedDate = date instanceof Date ? date : new Date(date);
  
  if (isNaN(parsedDate.getTime())) {
    throw new Error('Invalid date');
  }

  const year: string = String(parsedDate.getFullYear());
  const month: string = String(parsedDate.getMonth() + 1).padStart(2, '0');
  const day: string = String(parsedDate.getDate()).padStart(2, '0');
  const hours: string = String(parsedDate.getHours()).padStart(2, '0');
  const minutes: string = String(parsedDate.getMinutes()).padStart(2, '0');
  const seconds: string = String(parsedDate.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};