Last active
July 18, 2018 02:26
-
-
Save leaysgur/9a4c852253d270bab54c969e64199320 to your computer and use it in GitHub Desktop.
WebComponents to format date strings by Intl.DateTimeFormat()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FormatDate extends HTMLElement { | |
connectedCallback() { | |
this.attachShadow({ mode: 'open' }); | |
this._render(); | |
} | |
_render() { | |
const textContent = this._getBaseText(this.textContent); | |
const date = this._getFormatted( | |
textContent, | |
this.getAttribute('locale') || 'ja-JP', | |
this._getFormatOptions() | |
); | |
this.shadowRoot.innerHTML = ` | |
<span>${date}</span> | |
`; | |
} | |
_getBaseText(textContent) { | |
const match = textContent.match(/^(\d{4})(\d{2})/); | |
if (match === null) { | |
return textContent; | |
} | |
const [ , yyyy, mm ] = match; | |
return `${yyyy}-${mm}`; | |
} | |
_getFormatOptions() { | |
return ['year', 'month', 'day', 'hour', 'minute', 'second'].reduce((acc, cur) => { | |
const val = this.getAttribute(cur); | |
val !== null && (acc[cur] = val); | |
return acc; | |
}, {}); | |
} | |
_getFormatted(dateStr, locale, options) { | |
try { | |
const date = new Date(dateStr); | |
const formatter = new Intl.DateTimeFormat(locale, options); | |
return formatter.format(date); | |
} catch(err) { | |
console.error(err); | |
return dateStr; | |
} | |
} | |
} | |
export default FormatDate; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 2018/06/26 --> | |
<format-date | |
year="numeric" | |
month="2-digit" | |
day="2-digit" | |
> | |
2018-06-26T03:07:51.446Z | |
</format-date> | |
<!-- 2018年 --> | |
<format-date | |
year="numeric" | |
> | |
201806 | |
</format-date> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import FormatDate from './format-date.js'; | |
customElements.define('format-date', FormatDate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment