Javascript DateFormat for different timezones

后端 未结 9 2074
小蘑菇
小蘑菇 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:16

    You are clearly asking two questions in one, formatting and time zone. They need to be addressed separately. Formatting is pretty trivial, if none of the other answers will do for that you will have to be more specific.

    As for the time and time zone, if you have your server inject the UTC time, preferably as UNIX time in milliseconds, into the JavaScript, you can compare that to the time on the client machine, and thus work out how far from UTC the client is. Then you can calculate the time of any time zone you want.

    Edit: I actually didn't know JavaScript also had built in UTC time until I checked on the internet, neat.

    In any case, I suppose this is want you want:

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

    You can add in more patterns if you need.

提交回复
热议问题