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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27480262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:12:20  来源:igfitidea点击:

Get current date in DD-Mon-YYY format in JavaScript/Jquery

javascriptjquerydatedatetime

提问by Tushar

I need to get the date format as 'DD-Mon-YYYY' in javascript. I had asked a question, and it got marked duplicate to jQuery date formatting

我需要在 javascript 中获取日期格式为“DD-Mon-YYYY”。我问了一个问题,它被标记为与jQuery 日期格式重复

But, the answers provided in the question are to get the current date in "DD-MM-YYYY" format and not "DD-MON-YYYY". Secondly, I am not using datepicker plugin.

但是,问题中提供的答案是以“DD-MM-YYYY”格式而不是“DD-MON-YYYY”格式获取当前日期。其次,我没有使用 datepicker 插件。

Can you please help me as if how to get the current date in "DD-Mon-YYYY" format.

你能帮我看看如何以“DD-Mon-YYYY”格式获取当前日期。

回答by Ahmad

There is no native format in javascript for DD-Mon-YYYY.

javascript 中没有用于DD-Mon-YYYY.

You will have to put it all together manually.

您必须手动将它们放在一起。

The answer is inspired from : How to format a JavaScript date

答案灵感来自: How to format a JavaScript date

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

Date.prototype.toShortFormat = function() {

    let monthNames =["Jan","Feb","Mar","Apr",
                      "May","Jun","Jul","Aug",
                      "Sep", "Oct","Nov","Dec"];
    
    let day = this.getDate();
    
    let monthIndex = this.getMonth();
    let monthName = monthNames[monthIndex];
    
    let 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

回答by Klemen Tu?ar

Use the Moment.js library http://momentjs.com/It will save you a LOT of trouble.

使用 Moment.js 库http://momentjs.com/它会为你省去很多麻烦。

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

回答by Jerome Anthony

You can use toLocaleDateStringand hunt for a format that's close to DD-mmm-YYYY (hint: 'en-GB'; you just need to replace the spaces with '-').

您可以使用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);

回答by Yanga

Can be done with toLocaleDateString

可以用 toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

<script>
const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: '2-digit', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
document.write(formattedDate);
</script>

回答by Indranil Mondal

I've made a custom date string format function, you can use that.

我已经制作了一个自定义日期字符串格式函数,您可以使用它。

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., o[k]);
            }
        }
        return formattedDate;
    };

And now suppose you've :-

现在假设你已经:-

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

So to format this date you write:-

所以要格式化这个日期,你写:-

var formattedDate = getDateString(new Date(date), "d-M-y")

回答by RobG

Using the Intl object (or via toLocaleString) is somewhat problematic, but it can be made precise using the formatToPartsmethodand manually putting the parts in order, e.g.

使用 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());

Using reduceon the array returned by formatToPartstrims out the literals and creates an object with named properties that is then assigned to variables and finally formatted.

formatToParts返回的数组上使用reduce修剪掉文字并创建一个具有命名属性的对象,然后将其分配给变量并最终格式化。

This function doesn't always work nicely for languages other than English though as the short month name may have punctuation.

此功能并不总是适用于英语以外的语言,尽管短月份名称可能有标点符号。

回答by Anikesh Dhanokar

Pass data changeFormate(15/07/2020)

传递数据changeFormate(15/07/2020)

  changeFormate(date) {
let month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let incomingDateChnge: any = new Date(date);
let incomingDay = incomingDateChnge.getDate();
let incomingMonth = incomingDateChnge.getMonth();

let incomingYear = incomingDateChnge.getFullYear();
if (incomingDay < 10) {
  incomingDay = '0' + incomingDay;
}

incomingDateChnge = incomingDay + ' ' + month_names[incomingMonth] + ' ' + incomingYear;
return incomingDateChnge;
 }

回答by gtzinos

/*
  #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;
}

回答by Vince V.

the DD-MM-YYYY is just one of the formats. The format of the jquery plugin, is based on this list: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

DD-MM-YYYY 只是其中一种格式。jquery 插件的格式基于此列表:http: //docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Tested following code in chrome console:

在 chrome 控制台中测试了以下代码:

test = new Date()
test.format('d-M-Y')
"15-Dec-2014"

回答by Sakshi Nagpal

const date = new Date();

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