使用 JavaScript 获取特定的日期格式

Getting specific date format using JavaScript

本文关键字:日期 格式 JavaScript 获取 使用      更新时间:2023-09-26

我正在尝试将下面的数据格式更改为另一种形式。

这是我得到的date

var datetime =Thu Oct 03 2013 13:41:06 GMT+0530 (IST)

我怎样才能以这种格式获得date 03-10-2013 13:41 PM

为什么不写一个短函数来拆分日期字符串。然后,您可以按照您喜欢的任何顺序将它们重新粘在一起。

下面是一个快速示例:

function tidyDate(theDate) {
    // split up the string into parts separated by colons or whitespace
    var parts = theDate.toString().split(/[:'s]+/);
    // Get the number of the month - Don't forget that it's zero-indexed
    var month = theDate.getMonth() + 1;
    // Let's say that it's morning
    var AMPM = " AM";
    // But we should check whether it's after noon
    if (parseInt(parts[4]) >= 12){
        AMPM = " PM";
    }
    return parts[2] + "-" +  month + "-" + parts[3] + " " + parts[4] + ":" + parts[5] + AMPM;
}    
tidyDate(new Date());

返回:

03-10-2013 13:41 PM

您在那里看到的格式是将日期转换为字符串时使用的 JS 详细版本。如果您想自己指定格式,则需要分解日期的各个部分并使用各种日期方法将它们连接在一起,例如date.getYear() + '/' + date.getMonth()等。

或者,您可以使用诸如date之类的库.js它将为您执行此操作,例如:

myDate.toString("dd-mm-yyyy")

进一步阅读日期中的字符串.js

如果你想

纯JS中做到这一点,那么你必须做一些类似的事情

var ms = new Date("Thu Oct 03 2013 13:41:06 GMT+0530 (IST)");
var curr_date = (ms.getDate()< 10) ? "0" + ms.getDate() : ms.getDate();
var curr_month = (ms.getMonth()< 9) ? "0" + (ms.getMonth()+1) : ms.getMonth()+1;
var curr_year = ms.getFullYear();
var hours = ms.getHours();
var min = ms.getMinutes();
suf = (hours >= 12)? 'pm' : 'am';
hours = hours % 12;
alert(curr_date + "-" + curr_month + "-" + curr_year + "  " + hours + ":" + min + " " + suf);

演示

为简单起见,您可以尝试使用以下库

时刻.js

moment().format('DD-MM-YYYY, h:mm a');

试试这段代码

function dateFormat()
{
    var d = new Date();
    date = d.getDate();
    date = date < 10 ? "0"+date : date;
    mon = d.getMonth()+1;
    mon = mon < 10 ? "0"+mon : mon;
    year = d.getFullYear()
    return (date+"/"+mon+"/"+year);
}

并让我知道..

张贴的那将完全有助于你的事业..http://jsbin.com/OCikUZO/1/edit

function convertUTCDateToLocalDate(date) {
  alert('hi');
    var newDate = new Date(date.getTime());
    var offset = date.getTimezoneOffset() / 60;
    var hours = date.getHours();
    newDate.setHours(hours - offset);
    return newDate;   
}
var datetime = new Date("January 02, 2012 22:00:00 GMT+0530");
var date = convertUTCDateToLocalDate(new Date(datetime));
var now = date.toLocaleString();