Skip to content

Instantly share code, notes, and snippets.

@yuka2py
Created February 13, 2016 06:06
Show Gist options
  • Save yuka2py/ddfd7ee6d59c2607ce83 to your computer and use it in GitHub Desktop.
Save yuka2py/ddfd7ee6d59c2607ce83 to your computer and use it in GitHub Desktop.
日付をなんかうまいことパースしてくれるやつ。
let mapZenHan = () => {
let zen = ' 0123456789.,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY!?.,’”!#$%&’()=|‘@{}[]-*+:;¥_/?.,><'.split('');
let han = ' 0123456789.,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY!?.,\'"!#$%&\'()=|`@{}[]-*+:;\\_/?.,><'.split('');
let map = [];
for (let i = 0, len = src.length; i < len; i++) {
map.push([new RegExp(zen[i], 'g')], han[i])
}
return map;
};
/**
* 与えられた文字列を日付として評価して、Date Object を返す。
* 評価できない場合、false を返す。
*
* @param String string 日付として評価する文字列。
* @return Date
*/
export function parse(string) {
if (!string) return null;
//全角を半角に
string = ((s) => {
for (let i = 0, len = mapZenHan.length; i < len; i++) {
let [ matcher, replace ] = mapZenHan[i];
s = s.replace(matcher, replace);
}
return s;
})(string);
//空白で分割
let src = string.split(/[ ]+/);
let dsrc = '';
let tsrc = '';
//入力文字列の整理
if (src.length == 1)
{
dsrc = src.shift();
tsrc = '';
if (dsrc.search(/:/) != -1) {
tsrc = dsrc;
dsrc = '';
}
}
else if (src.length >= 2)
{
dsrc = src.shift();
tsrc = src.shift();
let other = src.shift();
//2つ目に数字が含まれて無い場合、3つ目に数字が含まれれば3つ目を使用。3つ目も数字が無ければ、時間指定無し
if (!tsrc.match(/\d+/g)) {
tsrc = (other && other.match(/\d+/g)) ? other : '';
}
}
//評価の材料として現在の日時を準備
let today = new Date();
let year = today.getFullYear();
let mon = today.getMonth();
let day = today.getDate();
let hour = 0; //today.getHours();
let min = 0; //today.getMinutes();
let sec = 0; //today.getSeconds();
//日付のパース
dsrc = dsrc.match(/\d+/g);
if (dsrc)
{
if (dsrc.length == 1)
{
day = dsrc.shift();
}
else if (dsrc.length == 2)
{
mon = dsrc.shift() - 1;
day = dsrc.shift();
}
else if (dsrc.length >= 3)
{
let yer = dsrc.shift();
mon = dsrc.shift() - 1;
day = dsrc.shift();
if (yer.toString().length >= 4)
{
year = yer;
}
else
{
if (yer > 70) year -= 100;
year = year.toString().substring(0, 4 - (yer.toString().length)) + yer;
}
}
}
//時間をパース
tsrc = tsrc.match(/\d+/g);
if (tsrc)
{
if (tsrc.length == 1)
{
hour = tsrc.shift();
}
else if (tsrc.length == 2)
{
hour = tsrc.shift();
min = tsrc.shift();
}
else if (tsrc.length >= 3)
{
hour = tsrc.shift();
min = tsrc.shift();
sec = tsrc.shift();
}
}
if (!dsrc && !tsrc) return null;
return new Date(year, mon, day, hour, min, sec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment