Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. # JavaScriptの日付オブジェクトを指定した書式でフォーマットする汎用ファンクションを作成します。
  2.  
  3. 日付オブジェクトを文字列に変換していくのではなく、指定したフォーマットの文字列に日付オブジェクトの対象の値を置換していくイメージです。
  4.  
  5. このやり方なら例えば曜日が必要な場合でも簡単に拡張できます。
  6.  
  7. // date: 日付オブジェクト
  8. // format: 書式フォーマット
  9. function formatDate (date, format) {
  10. format = format.replace(/yyyy/g, date.getFullYear());
  11. format = format.replace(/MM/g, ('0' + (date.getMonth() + 1)).slice(-2));
  12. format = format.replace(/dd/g, ('0' + date.getDate()).slice(-2));
  13. format = format.replace(/HH/g, ('0' + date.getHours()).slice(-2));
  14. format = format.replace(/mm/g, ('0' + date.getMinutes()).slice(-2));
  15. format = format.replace(/ss/g, ('0' + date.getSeconds()).slice(-2));
  16. format = format.replace(/SSS/g, ('00' + date.getMilliseconds()).slice(-3));
  17. return format;
  18. };
  19.  
  20. // 2017年1月2日3時4分5秒6ミリ秒
  21. var date = new Date(2017, 0, 2, 3, 4, 5, 6);
  22.  
  23. console.log(formatDate(date, 'yyyyMMdd')); // "20170102"
  24. console.log(formatDate(date, 'yyyyMMddHHmmssSSS')); // "20170102030405006"
  25. console.log(formatDate(date, 'yyyy/MM/dd')); // "2017/01/02"
  26. console.log(formatDate(date, 'yyyy-MM-dd')); // "2017-01-02"
  27. console.log(formatDate(date, 'HH:mm')); // "03:04"
  28. console.log(formatDate(date, 'HH:mm:ss:SSS')); // "03:04:05:006"
  29.  
  30.  
  31. ## 2017/1/2などのように、0埋めが不要な場合は以下ようにします。
  32.  
  33. function formatDate (date, format) {
  34. format = format.replace(/yyyy/g, date.getFullYear());
  35. format = format.replace(/M/g, (date.getMonth() + 1));
  36. format = format.replace(/d/g, (date.getDate()));
  37. format = format.replace(/H/g, (date.getHours()));
  38. format = format.replace(/m/g, (date.getMinutes()));
  39. format = format.replace(/s/g, (date.getSeconds()));
  40. format = format.replace(/S/g, (date.getMilliseconds()));
  41. return format;
  42. };
  43. // 2017年1月2日3時4分5秒6ミリ秒
  44. var date = new Date(2017, 0, 2, 3, 4, 5, 6);
  45.  
  46. console.log(formatDate(date, 'yyyy/M/d')); // "2017/1/2"
  47. console.log(formatDate(date, 'yyyy-M-d')); // "2017-1-2"
  48. console.log(formatDate(date, 'H:m')); // "3:4"
  49. console.log(formatDate(date, 'H:m:s:S')); // "3:4:5:6"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement