【问题标题】:converting time Stamp to date and Date to Time stamp formats将时间戳转换为日期和日期转换为时间戳格式
【发布时间】:2016-11-26 07:02:54
【问题描述】:

日期为:10/02/2014 (DD/MM/YYYY)。 怎么转成Timestamp格式??

以及如何更改日期的格式。当我编写如下代码时:

var current_date=new Date();  -->i got result like MM/DD/YYYY format.

我想要当前日期的 DD/MM/YYYY 格式。

【问题讨论】:

标签: javascript date timestamp


【解决方案1】:

使用dateFormat 库。

var current_date = new Date();
dateFormat(current_date, "dd/mm/yyyy");

这会以“dd/mm/yyyy”格式返回日期。

【讨论】:

  • 谢谢你的回应兄弟。它运作良好。@sainath batthala
【解决方案2】:

你来了

var current_date=new Date();
var timestamp = current_date.getTime();
var formatted_date = current_date.getDate() + "/" + current_date.getMonth() + 1 + "/" + current_date.getFullYear()

【讨论】:

    【解决方案3】:

    “时间戳”我猜你的意思是时间值,比如1391954400000

    要将日期字符串转换为日期,您需要对其进行解析。使用库或短函数。然后您可以获取时间值,它表示自 1970-01-01T00:00:00Z 以来的毫秒数:

    /* Parse date sting in d/m/y format
    ** @param {string} s - date string in d/m/y format
    **                     separator can be any non–digit character
    ** @returns {Date} If s is an invalid date, returned
    **                 Date has time value of NaN (invalid date)
    */
    function parseDMY(s) {
      var b = s.split(/\D/);
      var d = new Date(b[2], --b[1], b[0]);
      return d && d.getMonth() == b[1]? d : new Date(NaN);
    }
    
    // Valid date
    console.log(parseDMY('10/02/2014').getTime());
    
    // Invalid date
    console.log(parseDMY('14/20/2016').getTime());

    还有很多用于格式化日期的库(例如,Fecha.js 进行解析和格式化),或者再次,如果您只有一种格式,一个简单的函数就可以了:

    /* Return date string in format dd/mm/yyy
    ** @param {Date} d - date to format, default to today
    ** @returns {string} date in dd/mm/yyyy format
    */
    function formatDMY(d) {
      // Default to today
      d = d || new Date();
      return ('0' + d.getDate()).slice(-2) + '/' +
             ('0' + (d.getMonth() + 1)).slice(-2) + '/' +
             ('000' + d.getFullYear()).slice(-4);
    }
    
    console.log(formatDMY());
    console.log(formatDMY(new Date(2016,1,29)));

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 2020-02-23
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多