JavaScript Dateã®ã¿ã¤ã ã¾ã¼ã³æå®ã§ããªãåé¡ã¨ãã®å¯¾ç
JavaScriptã®Dateåã§ã¯ãã¿ã¤ã ã¾ã¼ã³ãå¤é¨ããæå®ã§ããªã
- JavaScriptã®Dateåã¯ãã¿ã¤ã ã¾ã¼ã³ã®æ
å ±ãæã£ã¦ã¯ãã¾ãããAPIã§å¤ããå¤æ´ãããã¨ã¯ã§ãã¾ããã
- getTimezoneOffset() ã¯ãããã©ãsetTimezoneOffset(timezone) ã¯ããã¾ããã
- getTimezoneOffset() ã®å¤ã¯å®è¡ç°å¢ã®ã¿ã¤ã ã¾ã¼ã³ã«ãªãã¾ãã
- getHours()ãgetMinutes()ã¯ãã¼ã«ã«ã®ã¿ã¤ã ã¾ã¼ã³ã«ãããæå»è¡¨ç¾ãè¿ãã®ã§ãå®è¡ç°å¢ã«ãã£ã¦çµæãç°ãªããåé¡ã«ãªãå ´åãããã¾ãã
- Dateã表示ç¨ã®æååã«å¤æããå¦çã®ãã¹ããæ¸ãã¦ããããCIç°å¢(CircleCI)ã§åãããã¨ãã«çµæãéã£ã¦ã¨ã©ã¼ã«ã
- å¤æAPIã®ä»æ§ã¨ãã¦ã¯ããå®è¡ç°å¢ã«åãããæå»è¡¨ç¾ãè¿ããã®ãæå¾ ã®åä½ãªã®ã§ãåãã¨ãã¦ã¯ééã£ã¦ããªãã®ã§ããããã¹ãã§ã¯å°ãã»ã»
- CIç°å¢ã®ã¿ã¤ã ã¾ã¼ã³ãå¤æ´ããéããããã©ãã¿ã¤ã ã¾ã¼ã³ã®è¨å®ã«ãã£ã¦å½±é¿ãåºãç¯å²ãææ¡ããããã«ãã¹ãã±ã¼ã¹ã¯ãããããªç°å¢ã§åããããã«ããæ¹ãããããªãã¨ãããã¨ã§ãç°å¢ã¯ããããªãæ¹åã§å¯¾çãæ¤è¨ã
const date = new Date( '2015-05-10T12:00:00.000Z' ); expect( date.getHours() ).toEqual(21); // ãã¼ã«ã«ã¿ã¤ã ã¾ã¼ã³ãJSTã®å ´åã¯åä½ããããä»ã®ç°å¢ã§ã¯éãçµæã«ãªãã
対ç
以ä¸ã®ããã«ãã¦ã¿ã¾ããã
- Dateã®ä»£ããã«ã date-with-offset ã使ãã
- Dateã«ã¿ã¤ã ã¾ã¼ã³æå®æ©è½ã追å ããã©ã¤ãã©ãªãDateã®APIã¨äºææ§ãããã®ã§ãã®ã¾ã¾ç½®ãæãããã¾ãã
- DateWithOffsetãnewããã¨ãã«ãstaticå¤æ°ããã¿ã¤ã ã¾ã¼ã³ãèªã¿è¾¼ãã§ä½¿ãã
- staticå¤æ°ã§æå®ããã¦ããã°ãã¡ããæå®ããªããã°ãã¼ã«ã«ã®ã¿ã¤ã ã¾ã¼ã³ã使ãã¾ãã
- ããã«ããããã¼ã«ã«ã¿ã¤ã ã¾ã¼ã³ã®å½±é¿ãåãããã¹ãã®å®è¡æã«ã®ã¿ãæå®ããã¿ã¤ã ã¾ã¼ã³ã§ãã¹ããå®è¡ããããã«ãªãã¾ãã
- æå®ããªãå ´åã¯æ®éã®Dateã¨åãåãã«ãªãã®ã§ããããã¯ã·ã§ã³ç°å¢ã§ã¯ãå®è¡ç°å¢ã«åãããæå»è¡¨ç¾ãè¿ããåä½ã¨ãªãã¾ãã
å ·ä½çã«ã¯ãããªã¦ã¼ãã£ãªãã£ãä½æã
import DateWithOffset from "date-with-offset" const defaultTimezoneOffset = new Date().getTimezoneOffset()*-1; export default class Dates { static date(iso8601String) { return new DateWithOffset( iso8601String, this.getTimezoneOffset() ); } static getTimezoneOffset() { return this.timezoneOffset != null ? this.timezoneOffset : defaultTimezoneOffset; } static setTimezoneOffset(timezoneOffset) { this.timezoneOffset = timezoneOffset; } static resetTimezoneOffset() { this.timezoneOffset = null; } }
ãã¼ã«ã«ã¿ã¤ã ã¾ã¼ã³ã«ä¾åãããã¹ããåä½ããã¨ããã¯ã以ä¸ã®ããã«ãããã¨ã§ãã©ã®ç°å¢ã§ãåãçµæãè¿ãããã«ãªãã¾ãã
beforeEach( ()=> Dates.setTimezoneOffset(540) ); afterEach( ()=> Dates.resetTimezoneOffset() ); it("ãã¼ã«ã«ã¿ã¤ã ã¾ã¼ã³ã«ä¾åãããã¹ã", () => { // ãã®ãã¹ãå ã§ã¯ããã¼ã«ã«ã¿ã¤ã ã¾ã¼ã³ãJSTã«ãªãã expect( Dates.date("2015-05-10T12:00:00.000Z").getHours() ).toEqual(21); });