javascript - 将日期对象更改为全文代表

时间:2015-07-26 10:39:16

标签: javascript date

我正在寻找一种方法将javascript Date对象转换为文本的文本表示,如下所示:

Sunday the 26th of July two thousand and fifteen

2 个答案:

答案 0 :(得分:1)

您可以在JavaScript中使用以下代码。只需在函数 return_formatted_date 中传递日期对象,此函数将根据需要返回文本表示。希望这有帮助!

        <script>
            function return_formatted_date(date){
                var text = "";
                var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
                var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                var centuryText = ["One", "Two", "Three","Four", "Five", "Six", "Seven", "Eight", "Nine"];
                var eleven_twenty = ["Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"];
                var hundred_suffix = ["","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"];
                text = weekday[date.getDay()] + " the ";
                var day = date.getDate();
                if(day==1){
                    text = text +  day + "st";
                }else if(day==2){
                    text = text + day + "nd";
                }else if(day==3){
                    text = text + day + "rd";
                }else{
                    text = text + day + "th";
                }
                text = text + " of " + months[date.getMonth()];
                var year = parseInt(date.getFullYear());
                var century = parseInt(year/1000);
                var hundred = parseInt(year/100)%10;
                var tens = parseInt(year)%100;
                if(century!=0){
                    text = text + " " + centuryText[century-1] + " thousand";
                }
                if(hundred!=0){
                    text = text + " " + centuryText[hundred-1] + " hundred";
                }
                if(tens!=0){
                    text = text + " and";
                    if(tens<10){
                        text = text + " " + centuryText[tens-1];
                    }else if(tens>=11&&tens<=20){
                        text = text + " " + eleven_twenty[tens-11];
                    }else{
                        var tens_up = tens/10;
                        var tens_down = tens%10;
                        if(tens_up!=0){
                            text = text + " " + hundred_suffix[tens_up-1];
                        }
                        if(tens_down!=0){
                            text = text + " " + centuryText[tens_down-1];
                        }
                    }
                }
                return text;
            }

        </script>

答案 1 :(得分:0)

将java脚本日期对象转换为字符串(即文本)的唯一方法是这样的:

var d = new Date();
var t = d.toString();

或使用:

var d = new Date();
var t = d.format("date-to-format");

我认为这篇文章会对你有所帮助:

How to format java script date