当前位置:首页 > JavaScript

js实现年月日

2026-01-31 08:19:31JavaScript

获取当前年月日

使用 Date 对象可以获取当前的年、月、日。以下是获取当前年月日的代码示例:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // 月份从0开始,需要加1
const day = date.getDate();

console.log(`${year}-${month}-${day}`);

格式化年月日

如果需要将日期格式化为特定的字符串形式,可以使用以下方法:

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

const today = new Date();
console.log(formatDate(today)); // 输出例如 "2023-09-15"

自定义日期操作

可以通过 Date 对象的方法对日期进行加减操作:

const date = new Date();
date.setDate(date.getDate() + 7); // 加7天
console.log(formatDate(date)); // 输出7天后的日期

使用第三方库

如果需要更复杂的日期操作,推荐使用 moment.jsdate-fns 等第三方库:

js实现年月日

// 使用 moment.js
const moment = require('moment');
console.log(moment().format('YYYY-MM-DD'));

// 使用 date-fns
const { format } = require('date-fns');
console.log(format(new Date(), 'yyyy-MM-dd'));

注意事项

  • 月份从0开始,1月对应0,12月对应11。
  • 使用 padStart 方法可以确保月份和日期的两位数格式。

标签: 年月日js
分享给朋友:

相关文章

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js 实现按钮点击

js 实现按钮点击

实现按钮点击的 JavaScript 方法 HTML 按钮元素 在 HTML 中创建一个按钮,可以通过 <button> 或 <input> 标签实现: <button…

js实现刷新页面

js实现刷新页面

刷新页面的方法 在JavaScript中,可以通过多种方式实现页面刷新。以下是几种常见的方法: 使用 location.reload() 调用 location.reload() 方法可以重新加载当…

js实现点击效果

js实现点击效果

实现点击效果的JavaScript方法 使用addEventListener绑定点击事件 通过document.getElementById或document.querySelector获取DOM元素…

js实现div隐藏

js实现div隐藏

使用CSS的display属性隐藏div 通过设置元素的display属性为none,可以完全隐藏div元素。这种方法不仅隐藏元素,还会从文档流中移除,不占据页面空间。 document.getEl…

js实现上传图片预览

js实现上传图片预览

使用FileReader实现图片预览 通过FileReader对象读取用户选择的图片文件,并将其显示在页面上。这种方法适用于现代浏览器。 // HTML部分 <input type="file…