Table of Contents
回复内容:
Home Backend Development PHP Tutorial javascript - JS中有类似PHP date()方法吗?

javascript - JS中有类似PHP date()方法吗?

Jun 06, 2016 pm 08:25 PM
javascript php

如题,想实现功能。
传入时间戳“1400000000”,返回格式:2015-01-01

PHP实现:date("Y-m-d H:i:s","1400000000");
javascript实现呢??

回复内容:

如题,想实现功能。
传入时间戳“1400000000”,返回格式:2015-01-01

PHP实现:date("Y-m-d H:i:s","1400000000");
javascript实现呢??

随便实现了一下,写的比较糙,但是可以实现

function getFormatDate(split,timeInMs){
  var curr=new Date();
  curr.setTime(timeInMs);
  var year=curr.getFullYear();
  var month=curr.getMonth()+1;
  var date=curr.getDate();
  
  var hours=curr.getHours();
  var minutes=curr.getMinutes();
  var seconds=curr.getSeconds();
  
  var formatDateStr=year+split[0]+month+split[0]+date+" "+hours+split[1]+minutes+split[1]+seconds;
  return formatDateStr;
}

var res=getFormatDate(["-",":"],1433456000345); //这里要输入13位数
console.log(res); // 2015-6-5 6:13:20
Copy after login

https://github.com/jacwright/date.format

自己实现的话可以看以上几位的,俺贴个插件。

http://momentjs.cn/

兼容大部分PHP里面date函数的实现:

<code>function date () {
    if (arguments.length == 0) {
        throw "date() expects at least 1 parameter, 0 given";
    }

    var format = arguments[0];
    var time = arguments.length > 1 ? new Date(arguments[1] * 1000) : new Date();

    var padding = function (str, length) {
        return "0000".substr(0, length - str.toString().length) + str;
    }

    return format.replace(/[a-z]/ig, function (c){
        var dayOfYear = function (time) {
            return (time.getTime() - (new Date(time.getFullYear(), 0, 1)).getTime()) / 86400000 >> 0;
        }

        var daysOfMonth = function (time) {
            var year = time.getFullYear();
            var month = time.getMonth();
            return ((new Date(year, month + 1, 1)).getTime() - (new Date(year, month, 1)).getTime()) / 86400000 >> 0;
        }

        var sign = function (num) {
            return num >= 0 ? "+" : "-";
        }

        switch (c) {
            case "d":
                return padding(time.getDate());
            case "D":
                return ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][time.getDay()];
            case "j":
                return time.getDate();
            case "l":
                return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][time.getDay()];
            case "N":
                return [7, 1, 2, 3, 4, 5, 6][time.getDay()];
            case "S":
                switch(time.getDate()) {
                    case 1:
                        return "st";
                    case 2:
                    case 22:
                        return "nd";
                    case 3:
                    case 23:
                        return "rd";
                }
                return "th";
            case "w":
                return time.getDay();
            case "z":
                return dayOfYear(time);
            case "W":
                return dayOfYear(time) / 7 >> 0;
            case "F":
                return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][time.getMonth()];
            case "m":
                return padding(time.getMonth() + 1, 2);
            case "M":
                return ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][time.getMonth()];
            case "n":
                return time.getMonth() + 1;
            case "t":
                return daysOfMonth(time);
            case "L":
                return dayOfyear(new Date(time.getFullYear() + 1, 0, 1)) == 365;
            case "Y":
                return time.getFullYear();
            case "y":
                return padding(time.getFullYear() % 100, 2);
            case "a":
                return time.getHours() >= 12 ? "am" : "pm";
            case "A":
                return time.getHours() >= 12 ? "AM" : "PM";
            case "g":
                return time.getHours() % 12;
            case "G":
                return time.getHours();
            case "h":
                return padding(time.getHours() % 12, 2);
            case "H":
                return padding(time.getHours(), 2);
            case "i":
                return padding(time.getMinutes(), 2);
            case "s":
                return padding(time.getSeconds(), 2);
            case "u":
                return time.getTime() % 1000 + "000";
            case "O":
                return sign(-time.getTimezoneOffset()) + padding(Math.abs(time.getTimezoneOffset()) / 60, 2) + "00";
            case "P":
                return sign(-time.getTimezoneOffset()) + padding(Math.abs(time.getTimezoneOffset()) / 60 >> 0, 2) + ":" + Math.abs(time.getTimezoneOffset()) % 60;
            case "Z":
                return -time.getTimezoneOffset();
            case "U":
                return time.getTime() / 1000 >> 0;
            case "o":
            case "B":
            case "e":
            case "I":
            case "T":
            case "c":
            case "r":
                throw c + " is not yet implemented.";
            default:
                return c;
         }
    })
}</code>
Copy after login

<code>// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
function formatDate(date, fmt){ //author: meizz
    fmt = fmt || 'yyyy-MM-dd hh:mm:ss';
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}</code>
Copy after login

不用谢我,我也是从其他地方抄的

<code>var unixTimestamp = new Date(1446027232 * 1000);
commonTime = unixTimestamp.toLocaleString();
</code>
Copy after login

希望这个也能帮到你一点。

有,不过不太好用。
另附其他语言版本

<code>Java    time
JavaScript    Math.round(new Date().getTime()/1000)
getTime()返回数值的单位是毫秒
Microsoft .NET / C#    epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
MySQL    SELECT unix_timestamp(now())
Perl    time
PHP    time()
PostgreSQL    SELECT extract(epoch FROM now())
Python    先 import time 然后 time.time()
Ruby    获取Unix时间戳:Time.now 或 Time.new
显示Unix时间戳:Time.now.to_i
SQL Server    SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
Unix / Linux    date +%s
VBScript / ASP    DateDiff("s", "01/01/1970 00:00:00", Now())
其他操作系统
(如果Perl被安装在系统中)    命令行状态:perl -e "print time"</code>
Copy after login

建议使用momentjs,出bug的机会小;不过有时间可以研究楼上自己写的扩展。

https://segmentfault.com/q/1010000000701472/a-1020000005044252?utm_source=Weibo
楼上代码都不错,这里也有一个,大同小异.

<code>function formatDate(now)   {     
              var   year=now.getYear();     
              var   month=now.getMonth()+1;     
              var   date=now.getDate();     
              var   hour=now.getHours();     
              var   minute=now.getMinutes();     
              var   second=now.getSeconds();     
              return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;    
  } </code>
Copy after login

可以试试这个函数。
改下这个就行。
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;

sdfsdfsd

<code>sdfsadfsd</code>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles