Javascript DateFormat for different timezones

后端 未结 9 2073
小蘑菇
小蘑菇 2020-12-16 16:42

I\'m a Java developer and I\'m used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone.

Date date = new Dat         


        
9条回答
  •  情歌与酒
    2020-12-16 17:14

    If you're just passing the raw TZ there's nothing really complicated about adjusting the hours. My example below is of course abbreviated. Yours may get quite long depending on how many patterns you'd handle.

    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());
            }
        });
    }
    

提交回复
热议问题