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

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

本文关键字:格式 获取 当前日期 DD-Mon-YYY 中以 JavaScript Jquery      更新时间:2023-09-26

我需要在javascript中将日期格式设置为"DD-Mon-YYYY"。我问了一个问题,它被标记为与jQuery日期格式重复

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

您能否帮助我,好像如何以"DD-Mon-YYYY"格式获取当前日期。

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

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

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

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

可以用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>

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

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")

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

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

无需 JQuery。

const date = new Date();
date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

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

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

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

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

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

test = new Date()
test.format('d-M-Y')
"15-Dec-2014"
/*
  #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;
}

传递数据更改格式(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;
 }

下面是一个简单的解决方案,使用 TypeScript:

  convertDateStringToDate(dateStr) {
    //  Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
    let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    let date = new Date(dateStr);
    let str = date.getDate()
                + '/' + months[date.getMonth()]
                + '/' + date.getFullYear()
    return str;
  }
(是的,

我知道这个问题是关于 JavaScript 的,但我相信我不会是唯一一个遇到这篇文章的 Angular 开发人员!

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

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var currDate= new Date();
var newDate=currDate.toLocaleDateString();
var splitNewDate= newDate.split('/');
var formatDate= splitNewDate[1] + '-'+ monthNames[splitNewDate[0]] +'-'+ splitNewDate[2];
console.log(formatDate);

//convert DateTime result in jquery mvc 5 using entity fremwork 
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    
function DateAndTime(date) {
 
    var value = new Date
        (
        parseInt(date.replace(/(^.*'()|([+-].*$)/g, ''))
    ); 
    var dat = value.getDate() +
        "-" +
        monthNames[value.getMonth()] +
        "-" +
        value.getFullYear();
    var hours = value.getHours();
    var minutes = value.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return { Date: dat, Time: strTime };
}
// var getdate = DateAndTime(StartDate);
//var Date = getdate.Date;//here get date
//var time = getdate.Time;//here get Time
//alert(Date)

试试这个。

function dateFormat(D) {
  const monthNames = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];
  const day = D.getDate();
  const monthIndex = D.getMonth();
  const monthName = monthNames[monthIndex];
  const year = D.getFullYear();
  return `${day}-${monthName}-${year}`;
}
// Write Javascript code!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS ${dateFormat(new Date('2023-07-05'))}</h1>`;
<div id="app"></div>

var date = new Date();
console.log(date.toJSON().slice(0,10).replace(new RegExp("-", 'g'),"/" ).split("/").reverse().join("/")+" "+date.toJSON().slice(11,19));

输出 : 01/09/2016 18:30:00

            var today = new Date();           
            var formattedtoday = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
            
            alert(formattedtoday);

使用日期格式 dd-MM-yy .它将输出如下:2014 年 12 月 16 日。