在javascript中将Json时间戳转换为正常日期和时间

发布于 2024-12-28 06:53:36 字数 2053 浏览 2 评论 0原文

我有一个 Json 时间戳,我想使用 javascript 将其转换为简单的日期时间格式。

我需要以下格式的日期和时间:dd-mm-yyyy hr:mn

这是我希望提取时间戳的示例 json 日期:“timestamp”:1326439500

{
   "count": 2,
   "d": [
      {
         "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
         "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309201303",
         "timestamp": 1326439500,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "2388575404943858468"
      },
      {
         "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
         "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309198933",
         "timestamp": 1326439320,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "16209851193593872066"
      }
   ]
} 

I have a Json timestamp that I would like to convert into simple date time format using javascript.

I need the date and time in the following format : dd-mm-yyyy hr:mn

Here is an example json date from i wish to extract the timestamp: "timestamp": 1326439500

{
   "count": 2,
   "d": [
      {
         "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
         "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309201303",
         "timestamp": 1326439500,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "2388575404943858468"
      },
      {
         "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
         "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309198933",
         "timestamp": 1326439320,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "16209851193593872066"
      }
   ]
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挽你眉间 2025-01-04 06:53:36

日期以自纪元以​​来的毫秒数形式返回。下面的代码创建一个 JS 日期对象:

var d = new Date(1245398693390);
var formattedDate = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var formattedTime = hours + ":" + minutes;

formattedDate = formattedDate + " " + formattedTime;

这是一个工作小提琴

编辑1

自从很久以前发布这个答案以来已经发生了很多变化(尽管原始答案仍然有效)。在 ES6 引入 const/let 和模板文字之后,一种稍微简洁的方法是:

const d = new Date(1245398693390);
let formattedDate = `${d.getDate()}-${d.getMonth()}-${d.getFullYear()}`;
const hours = d.getHours().toString().padStart(2, 0);
const minutes = d.getMinutes().toString().padStart(2, 0);
const formattedTime = `${hours}:${minutes}`;

formattedDate = `${formattedDate} ${formattedTime}`;

这是 一个工作小提琴

您还可以通过稍微降低可读性来使代码更加简洁:

function getFormattedDate()  {
    const padWithZero = (num, targetLength) => String(num).padStart(targetLength, '0');
    const d = new Date(1245398693390);
    return `${d.getDate()}-${d.getMonth()}-${d.getFullYear()} ${padWithZero(d.getHours(), 2)} ${padWithZero(d.getMinutes(), 2)}`;
}

这是一个工作小提琴

人们还可以使用 .toLocaleString() 并从那里挑选出所需的元素。

The date is being returned as milliseconds since epoch. The code below creates a JS date object:

var d = new Date(1245398693390);
var formattedDate = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var formattedTime = hours + ":" + minutes;

formattedDate = formattedDate + " " + formattedTime;

Here's a working fiddle.

EDIT 1

Much has changed since this answer was posted so long ago (although the original answer is still valid). A slightly cleaner way of doing this after ES6 introduced const/let and template literals would be:

const d = new Date(1245398693390);
let formattedDate = `${d.getDate()}-${d.getMonth()}-${d.getFullYear()}`;
const hours = d.getHours().toString().padStart(2, 0);
const minutes = d.getMinutes().toString().padStart(2, 0);
const formattedTime = `${hours}:${minutes}`;

formattedDate = `${formattedDate} ${formattedTime}`;

Here's a working fiddle.

You could also make the code a bit more terse by making it only slightly less readable:

function getFormattedDate()  {
    const padWithZero = (num, targetLength) => String(num).padStart(targetLength, '0');
    const d = new Date(1245398693390);
    return `${d.getDate()}-${d.getMonth()}-${d.getFullYear()} ${padWithZero(d.getHours(), 2)} ${padWithZero(d.getMinutes(), 2)}`;
}

Here's a working fiddle.

One could also play with .toLocaleString() and pick out the needed elements from there.

番薯 2025-01-04 06:53:36

扩展 Date 的原型以包含如下所示的格式函数(或者查找或创建您自己的函数):

Date.prototype.format = function (formatString) {
    // Returns a formatted date string
    var month = this.getMonth() + 1,
        day = this.getDate(),
        year = this.getFullYear(),
        hours24 = this.getHours(),
        hours = (hours24 === 0 ? 12 : hours24 > 12 ? hours24 - 12 : hours24),
        meridiem = hours24 >= 12 ? "PM" : "AM",
        minutes = this.getMinutes(),
        seconds = this.getSeconds();

    return formatString.replace(/(MM)/g, month.padLeft(2, '0'))
        .replace(/(M)/g, month)
        .replace(/(dd)/g, day.padLeft(2, '0'))
        .replace(/(d)/g, day)
        .replace(/(yyyy)/ig, year)
        .replace(/(yy)/ig, year.toString().substring(2, 4))
        .replace(/(hh)/g, hours.padLeft(2, '0'))
        .replace(/(h)/g, hours)
        .replace(/(HH)/g, hours24.padLeft(2, '0'))
        .replace(/(H)/g, hours24)
        .replace(/(mm)/g, minutes.padLeft(2, '0'))
        .replace(/(m)/g, minutes)
        .replace(/(ss)/g, seconds.padLeft(2, '0'))
        .replace(/(s)/g, seconds)
        .replace(/(tt)/g, meridiem.toLowerCase())
        .replace(/(TT)/g, meridiem);
};

然后,要将时间戳转换为所需的格式,dd-mm-yyyy hr:mn (如您的评论中所述),您将执行以下操作:

var dateString = new Date(timestamp).format("dd-MM-yyyy hh:mm");

[编辑] 这是随附的 pad 功能:

Number.prototype.padLeft = function (width, padChar) {
    // Returns a padded string
    padChar = padChar || ' ';
    var value = this.toString();
    while (value.length < width) {
        value = padChar + value;
    }
    return value;
};

Extend Date's prototype to include a format function like so (or find or create your own):

Date.prototype.format = function (formatString) {
    // Returns a formatted date string
    var month = this.getMonth() + 1,
        day = this.getDate(),
        year = this.getFullYear(),
        hours24 = this.getHours(),
        hours = (hours24 === 0 ? 12 : hours24 > 12 ? hours24 - 12 : hours24),
        meridiem = hours24 >= 12 ? "PM" : "AM",
        minutes = this.getMinutes(),
        seconds = this.getSeconds();

    return formatString.replace(/(MM)/g, month.padLeft(2, '0'))
        .replace(/(M)/g, month)
        .replace(/(dd)/g, day.padLeft(2, '0'))
        .replace(/(d)/g, day)
        .replace(/(yyyy)/ig, year)
        .replace(/(yy)/ig, year.toString().substring(2, 4))
        .replace(/(hh)/g, hours.padLeft(2, '0'))
        .replace(/(h)/g, hours)
        .replace(/(HH)/g, hours24.padLeft(2, '0'))
        .replace(/(H)/g, hours24)
        .replace(/(mm)/g, minutes.padLeft(2, '0'))
        .replace(/(m)/g, minutes)
        .replace(/(ss)/g, seconds.padLeft(2, '0'))
        .replace(/(s)/g, seconds)
        .replace(/(tt)/g, meridiem.toLowerCase())
        .replace(/(TT)/g, meridiem);
};

Then, to convert the timestamp into the desired format, dd-mm-yyyy hr:mn (as mentioned in your comment), you'd do the following:

var dateString = new Date(timestamp).format("dd-MM-yyyy hh:mm");

[Edit] Here's the accompanying pad function:

Number.prototype.padLeft = function (width, padChar) {
    // Returns a padded string
    padChar = padChar || ' ';
    var value = this.toString();
    while (value.length < width) {
        value = padChar + value;
    }
    return value;
};
喜你已久 2025-01-04 06:53:36
<script>
var timestamp=1326439320;
var date=new Date(timestamp);
var hours = date.getHours(); // minutes part from the timestamp
var minutes = date.getMinutes(); // seconds part from the timestamp
var seconds = date.getSeconds(); // will display time in 10:30:23 format
 var formattedTime = hours + ':' + minutes + ':' + seconds;
alert(formattedTime);
</script>
<script>
var timestamp=1326439320;
var date=new Date(timestamp);
var hours = date.getHours(); // minutes part from the timestamp
var minutes = date.getMinutes(); // seconds part from the timestamp
var seconds = date.getSeconds(); // will display time in 10:30:23 format
 var formattedTime = hours + ':' + minutes + ':' + seconds;
alert(formattedTime);
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文