序文
JavaScriptの日付フォーマットは、毎日の開発では非常に一般的です。そのため、以下にJavaScript Time Format Format関数を使用する2つの例を共有します。見てみましょう。
方法1
date.prototype.pattern = function(fmt){var o = {"m+":this.getmonth()+1、// month "d+":this.getdate()、// date "h+":this.gethours()%12 == 0? 12:this.gethours()%12、// hour "h+":this.gethours()、// hour "m+":this.getminutes()、// min "s+":this.getseconds()、// second "q+":math.floor((this.getmanth()+3)/3) var week = {"0": "/u65e5"、 "1": "/u4e00"、 "2": "/u4e8c"、 "3": "/u4e09"、 "4": "/u56db"、 "5": "/u4e94"、 "6": "/u516d"}; if(/(y+)/。test(fmt)){fmt = fmt.Replace(regexp。$ 1、(this.getTullear()+"")。 } if(/(e+)/。test(fmt)){fmt = fmt.Replace(regexp。$ 1、((regexp。$ 1.LENGTH> 1)?(regexp。$ 1.LENGTH> 2? "/u661f/u671f": "/u5468"): ")") ") } for(o in o){if(new regexp( "("+ k+ ")")。test(fmt)){fmt = fmt.replace(regexp。$ 1、(regexp。$ 1. $ 1.== 1)?(o [k]):(( "00"+ o [k])。 }} fmt; }呼び出し方法
var date = new Date(); window.alert(date.pattern( "yyyy-mm-dd hh:mm:ss"));
方法2:
//日付を延長し、指定された形式の月(m)、日(d)、時間(h)、数分(m)、秒(s)、および1-2プレースホルダーに使用できます。 date())。format( "yyyy-mm-dd hh:mm:ss.s")==> 2006-07-02 08:09:04.423 //(new Date())。 "M+":this.getMonth()+1、// month "d+":this.getDate()、// day "h+":this.gethours()、// hours "m+":this.getminutes()、// min "s+":this.getSeconds()、// sense 「S」:this.getMilliseConds()// milliseconds}; if(/(y+)/.test(fmt)))fmt = fmt.Replace(regexp。$ 1、(this.getTullear() + "").substr(4 -regexp。$ 1. length)); for(o in o)if(new regexp( "(" + k + ")")。test(fmt))fmt = fmt.replace(regexp。$ 1、(regexp。$ 1.LENGTH == 1)?(o [k]):(( "00" + o [k])。 FMTを返します;}
呼び出し方法:
var harooms1 = new date()。format( "yyyy-mm-dd"); var harooms2 = new date()。形式( "yyyy-mm-dd hh:mm:ss");アラート(harooms1);アラート(harooms2);
要約します
上記はこの記事に関するすべてです。上記の2つの方法はインターネットからのもので、両方とも検証とテスト後に利用できます。また、より便利です。それらを使用すると、それらをカプセル化できます。あなたの関数でそれらを直接呼び出すだけです。これらの2回のフォーマット関数はまだ比較的良いです!それがあなたの勉強や仕事に役立つことを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとってください。