Last active
August 29, 2015 14:05
-
-
Save fddcddhdd/bd0d6d15ecc182501b4e to your computer and use it in GitHub Desktop.
kintone用の生年月日(日付フィールド)から、年齢を計算する
This file contains 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
// 20140813 kintone用javascript作成 | |
// 生年月日(日付フィールド)から、年齢を計算する | |
// 以下のサンプルコードだと、うるう年を考えていないので自作した | |
// https://cybozudev.zendesk.com/hc/ja/articles/202640900-%E7%B5%8C%E9%81%8E%E5%B9%B4%E6%95%B0%E3%82%92%E8%A1%A8%E7%A4%BA%E3%81%99%E3%82%8B | |
(function() { | |
// 生年月日が入っているフィールドコード名 | |
const BIRTHDAY_FIELD_NAME = '生年月日'; | |
"use strict"; | |
// 現在の年齢計算する関数 | |
function getYearMonth(arg_yyyy_mm_dd) { | |
//本日の日付を取得 | |
var today=new Date(); | |
// 肝心の年齢計算について | |
// 年月日の日は、そのまま引き算。 | |
// 年月日の月は、2ケタ左シフトして(100倍にする。1月は0なので+100からスタート)から、引き算。 | |
// 年月日の年は、4ケタ左シフトして(1万倍にする)から、引き算。 | |
// この計算方法の優れた所は、年・月・日を単独で計算して、足らなかったら上位からマイナスするという点! | |
// 単純ながら、確実な年齢計算が出来る優れたアルゴリズムです! | |
// ちなみに日数計算はできません。あくまで年数計算のみ | |
// 参照URL:http://d.hatena.ne.jp/toku-hiro/20070824 | |
today=today.getFullYear()*10000+today.getMonth()*100+100+today.getDate(); | |
// ハイフンをけずる(yyyy-mm-dd → yyyymmdd) | |
var birthday=parseInt(arg_yyyy_mm_dd.replace(/-/g, '')); | |
// 単純に引き算して、下4ケタを切り捨てて、年部分だけを返す | |
return(Math.floor((today-birthday)/10000)); | |
} | |
// レコード詳細表示 | |
kintone.events.on(['app.record.detail.show'], function (event) { | |
var record = event.record; // 保存前の画面上のレコード | |
// 生年月日 | |
var emBirthDay = kintone.app.record.getFieldElement(BIRTHDAY_FIELD_NAME); | |
// 年齢を表示するためのラベルを生成 | |
var emLabel = document.createElement("label"); | |
var emDiv = document.createElement("span"); | |
emBirthDay.appendChild(emDiv); | |
// 半角スペース的にちょっと間を開ける | |
emBirthDay.parentNode.style.width = (parseInt(emBirthDay.parentNode.style.width) + 50) + 'px'; | |
emDiv.appendChild(emLabel); | |
var valBirthday = getYearMonth(record[BIRTHDAY_FIELD_NAME]['value']); | |
emLabel.appendChild(document.createTextNode("(" + valBirthday + "歳)")); | |
return event; | |
}); | |
// レコード一覧表示 | |
kintone.events.on(['app.record.index.show'], function (event) { | |
// レコード配列をローカル変数に格納 | |
var records = event.records; | |
var emBirthDay = kintone.app.getFieldElements(BIRTHDAY_FIELD_NAME); | |
// レコード数の分だけループ | |
for (var i = 0; i < records.length; i++) { | |
var record = records[i]; | |
// 値の取得 | |
var record_data = record[BIRTHDAY_FIELD_NAME]['value']; | |
// DOM要素の取得し、年齢を追加 | |
var part = emBirthDay[i]; | |
part.innerHTML = record_data + "(" + getYearMonth(record_data) + "歳)"; | |
} | |
return event; | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment