代码之家  ›  专栏  ›  技术社区  ›  Elie

不同时区的Javascript日期格式

  •  10
  • Elie  · 技术社区  · 16 年前

    Date date = new Date();
    
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    
    sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    System.out.println(sdf.format(date)); // Prints date in Los Angeles
    
    sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
    System.out.println(sdf.format(date)); // Prints same date in Chicago
    

    SimpleDataFormat在Java中是一个非常简洁的解决方案,但不幸的是,我在Javascript中找不到任何类似的替代方案。

    我在延长原型的日期 做同样的事。我有Unix格式的日期,但我想在不同的时区格式。

    Date.prototype.format = function(format, timezone) {
        // Now what?
        return formattedDate;
    }
    

    我正在寻找一个整洁的方式来做这件事,而不是黑客。

    谢谢

    8 回复  |  直到 16 年前
        1
  •  17
  •   j4ys0n    5 年前

    console.log(new Date().toLocaleDateString('en-US', {timeZone: 'America/Denver'}))
    // 11/13/2018
    console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/Denver'}))
    // 2:30:54 PM
    console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/New_York'}))
    // 4:31:26 PM
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

        2
  •  3
  •   Garrett    16 年前

    通用日期的ISO扩展格式为YYYY-MM-DD,时间的ISO扩展格式为hh:MM:ss。任何一种格式都可以在世界范围内明确地理解。

    另请参见: http://jibbering.com/faq/#dates

        3
  •  2
  •   Pointy    16 年前

    http://www.datejs.com/

    您可以像这样计算在执行环境中时区偏移量的设置:

    var local = new Date();
    var utc = Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds());
    var tz = (utc - local.getTime()) / (60 * 60 * 1000);
    
        4
  •  1
  •   mwilcox    16 年前

    如果你只是通过了原始时间,那么调整时间并没有什么复杂的事情。

    Date.prototype.format = function(format, tzAdjust) {
        // adjust timezone
        this.setHours(this.getHours()+tzAdjust)
        // pad zero helper - return "09" or "12"
        var two = function(s){ return s+"".length==1 ? "0"+s : s+""; }
        // replace patterns with date numbers
        return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
            switch(pattern){
                case "d" : return this.getDate();
                case "dd" : return two(this.getDate());
            }
        });
    }
    
        5
  •  1
  •   Már Örlygsson    16 年前

    试图(稍微)改进mwilcox的建议:

    Date.prototype.format = function(format, tzAdjust) {
    
        // get/setup a per-date-instance tzDate object store
        var tzCache = this.__tzCache = this.__tzCache || (this.__tzCache = {});
    
        // fetch pre-defined date from cache 
        var tzDate = tzCache[tzAdjust];
        if ( !tzDate )
        {
          // on miss - then create a new tzDate and cache it
          tzDate = tzCache[tzAdjust] = new Date( this );
          // adjust by tzAdjust (assuming it's in minutes 
          // to handle those weird half-hour TZs :) 
          tzDate.setUTCMinutes( tzDate.getUTCMinutes()+tzAdjust );
        }
    
        return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
                   // replace each format tokens with a value 
                   // based on tzDate's corresponding UTC property
                 });
    }
    
        6
  •  1
  •   aaaaaaaaaaaa    16 年前

    很明显,你在一个问题中问了两个问题:格式和时区。它们需要分开处理。格式化是相当琐碎的,如果没有其他的答案可以做到这一点,你将不得不更具体。

    编辑:事实上,我不知道JavaScript也在UTC时间构建,直到我在网上查到,整洁。

    无论如何,我想这就是你想要的:

    Date.prototype.format=function(format,timezone){
        var obj=new Date(this.getTime()+this.getTimezoneOffset()*60000+timezone*3600000);
        var two=function(s){
            return s<10?"0"+s:s+"";
        }
        return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
            switch(pattern){
                case "dd" : return two(obj.getDate());
                case "MM" : return two(obj.getMonth()+1);
                case "yyyy" : return obj.getFullYear();
                case "hh" : return two(obj.getHours());
                case "mm" : return two(obj.getMinutes());
                case "ss" : return two(obj.getSeconds());
            }
        });
    }
    

    如果需要,可以添加更多模式。

        7
  •  0
  •   KaptajnKold    14 年前

    因此,没有“整洁”的方法来解决你的问题。

        8
  •  0
  •   Henrik N    10 年前

    如前所述,没有任何合理的内在因素。

    至于libs,有 Moment Timezone 对于 Moment.js .

    下面是一个带有示例的JSfiddle: http://jsfiddle.net/kunycrkb/

    相同的内联代码:

    var m = moment("2014-06-01T13:05:00Z");
    var f = "HH:mm z";
    
    $("#results").text(m.tz("UTC").format(f) + " is " + m.tz("EST").format(f) +  "!");
    
        9
  •  0
  •   Dark Light    5 年前

    因为我的要求是一个打字解决方案,但我在这里绊倒了我使用 this answer 写我的typescript函数。

    const formatDateString = (date_or_ts:Date|number):string=>{
        let obj:Date;
    
        if(typeof date_or_ts === "number"){
            obj = new Date(date_or_ts*1000);
            // obj=new Date(obj.getTime()+obj.getTimezoneOffset()*60000+timezone*3600000);
        }else{
            obj = date_or_ts;
        }
        const format = "dd-MM-yyyy hh:mm:ss";
        let two=function(s:number){
            return s<10?"0"+s:s+"";
        }
        return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
            const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            switch(pattern){
                case "dd" : return two(obj.getDate()).toString();
                case "MM" : return months[obj.getMonth()];
                case "yyyy" : return obj.getFullYear().toString();
                case "hh" : return two(obj.getHours()).toString();
                case "mm" : return two(obj.getMinutes()).toString();
                case "ss" : return two(obj.getSeconds()).toString();
                default: return "";
            }
        });
    }