JavaScript/Jquery中获取当前日期的DD-Mon-YYY格式

58
我需要在JavaScript中获得日期格式为“DD-Mon-YYYY”。 我曾经询问过这个问题,但它被标记为jQuery日期格式化的重复问题。
但是,该问题提供的答案是以“DD-MM-YYYY”格式获取当前日期,而不是“DD-MON-YYYY”格式。 其次,我没有使用datepicker插件。
请问如何在“DD-Mon-YYYY”格式中获得当前日期。

目前被接受的答案过于复杂。我已经编辑了另一个答案,我认为它更好地回答了您的问题。你能看一下吗? - Dan Dascalescu
18个回答

84

Javascript中没有本地格式为DD-Mon-YYYY 的格式。

你需要手动把它们全部拼凑在一起。

参考答案来自:如何在JavaScript中格式化日期?

// Attaching a new function  toShortFormat()  to any instance of Date() class

Date.prototype.toShortFormat = function() {

    const monthNames = ["Jan", "Feb", "Mar", "Apr",
                        "May", "Jun", "Jul", "Aug",
                        "Sep", "Oct", "Nov", "Dec"];
    
    const day = this.getDate();
    
    const monthIndex = this.getMonth();
    const monthName = monthNames[monthIndex];
    
    const year = this.getFullYear();
    
    return `${day}-${monthName}-${year}`;  
}

// Now any Date object can be declared 
let anyDate = new Date(1528578000000);

// and it can represent itself in the custom format defined above.
console.log(anyDate.toShortFormat());    // 10-Jun-2018

let today = new Date();
console.log(today.toShortFormat());     // today's date


56
你可以使用toLocaleDateString并寻找一个接近DD-mmm-YYYY的格式(提示:'en-GB';你只需要将空格替换为'-')。

const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: 'numeric', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
console.log(formattedDate);


我的输出格式是Dec-11,-2019,这不是我期望的。请帮我解决。 - Sujatha Girijala
@SujathaGirijala,你找到解决方案了吗? - Amy Doxy
1
@SujathaGirijala 这可能是因为您使用的语言环境不同。在这个例子中使用的是'en-GB',它应该会给您显示DD Mon YYYY。如果您使用'en-US'语言环境,则会显示Mon DD, YYYY。 - Calsal
唉,今天对我来说返回的是"2023年9月12日"。对于所有给这个点赞的56个人,我感到非常抱歉。 - undefined

24

使用Moment.js库 http://momentjs.com/ 它将为你节省大量麻烦。


moment().format('DD-MMM-YYYY');

2
它还会使你的代码变得臃肿(https://github.com/moment/moment/issues/3376),而且在JavaScript核心可以在不使用库的情况下解决问题时是不必要的(https://dev59.com/Zl4c5IYBdhLWcg3w1dPx#27480577)。 - Dan Dascalescu
1
当然。还有一个非常优秀的 date-fns 库 https://date-fns.org。我是说,现在有了今天的 npm 包,自己编写代码几乎没有意义。 - Klemen Tusar
有大量的日期库,每一个都应该有一个答案吗?其中许多比moment.js小得多。 - RobG
@RobG 的确现在有了,但是回到2014年,当我回答这个问题时,实际上没有太多可以玩的东西。 - Klemen Tusar

15

这个是"2023年9月12日" - undefined

4
我已经编写了一个自定义日期字符串格式的函数,你可以使用它。
var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
             "H+": getPaddedComp(date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "b+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

现在假设你已经:

    var date = "2014-07-12 10:54:11";

所以,要格式化这个日期,您需要编写:-
var formattedDate = getDateString(new Date(date), "d-M-y")

你不需要自己编写日期函数。Date对象已经有一个方法可以做到OP所要求的功能。链接 - Dan Dascalescu
谢谢,上面的答案在我的语言环境中不起作用,但是你的可以正常工作! - Mikhail Kh

3

默认情况下,new Date().toString()总是返回 'Sun Dec 12 2021...',因此:

d=new Date();
s=d.getDate()+'-'+d.toString().substr(4,3)+'-'+d.getFullYear();

console.log(s);

无需使用 JQuery。

2
const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

虽然这可能回答了问题,但最好添加一些描述,说明这个答案如何帮助解决问题。请阅读如何撰写一个好的答案以了解更多信息。 - Roshana Pitigala
...或者你可以改进使用toLocaleDateString的现有答案(https://dev59.com/Zl4c5IYBdhLWcg3w1dPx#27480577). - Dan Dascalescu

2

使用Intl对象(或通过toLocaleString)有些问题,但可以使用formatToParts方法精确地解决,并手动按顺序放置部分,例如:

function formatDate(date = new Date()) {
  let {day, month, year} = new Intl.DateTimeFormat('en', {
    day:'2-digit',
    month: 'short',
    year: 'numeric'
  }).formatToParts(date).reduce((acc, part) => {
    if (part.type != 'literal') {
      acc[part.type] = part.value;
    }
    return acc;
  }, Object.create(null));
  return `${day}-${month}-${year}`;
}

console.log(formatDate());

使用reduce处理由formatToParts返回的数组,可以去掉文字,并创建一个带有命名属性的对象,然后将其分配给变量并最终格式化。
但是,对于英语以外的语言,此函数并不总是有效,因为短月份名称可能带有标点符号。

完美的答案!其它所有答案都会以不同的顺序产生结果。 - Sushin Pv

1
/*
  #No parameters
  returns a date with this format DD-MM-YYYY
*/
function now()
{
  var d = new Date();
  var month = d.getMonth()+1;
  var day = d.getDate();

  var output = (day<10 ? '0' : '') + day + "-" 
              + (month<10 ? '0' : '') + month + '-'
              + d.getFullYear();

  return output;
}

这是一个非常低质量的答案:请解释一下你的代码所做的事情。此外,此代码不接受参数,但需要一个全局变量“d”。最后,它没有回答OP的问题:YYYY/MM/DD与所要求的DD-Mon-YYY不同。 - wintvelt

1

是的,我了解日期格式,但是如何将当前日期转换为dd-mon-yyyy格式呢?例如,我想以15-Dec-2014的格式获取当前日期。 - Tushar
通常情况下这应该可以工作(在控制台中测试过):test = new Date(); test.format('d-M-Y') - Vince V.
1
同意。这很好,但格式不是一个函数。 - roberto tomás
6
在控制台执行以下代码: TypeError: test.format 不是一个函数 test = new Date() test.format('d-M-Y'); - Smile
2
this is JS not Java - Felix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接