All files date.ts

95% Statements 19/20
100% Branches 0/0
94.11% Functions 16/17
95% Lines 19/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47        1x                 1x 16x 1x 1x 1x 3x     1x 3x   1x 3x   1x 3x   1x 3x   1x 3x     16x     26x            
/*
簡易日付処理。
[注意] 規模が大きくなれば moment 等を導入する
*/
import * as number from './number';
 
/**
 * なんちゃって書式処理
 *
 * @param format y*, M*, d*, H*, m*, s*
 *        https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/custom-date-and-time-format-strings
 * @param date
 */
export function format(format: string, date: Date) {
	const map: { [key: string]: (s: string) => string } = {
		'y': s => (date.getFullYear() - 2000).toString(), // getYaer が ts にないっていうね...
		'yy': s => number.padding(date.getFullYear() - 2000, 2, '0'),
		'yyy': s => number.padding(date.getFullYear(), 3, '0'),
		'yyyy': s => number.padding(date.getFullYear(), 4, '0'),
		'yyyyy': s => number.padding(date.getFullYear(), 5, '0'),
 
		'M': s => (date.getMonth() + 1).toString(),
		'MM': s => number.padding(date.getMonth() + 1, 2, '0'),
 
		'd': s => date.getDate().toString(),
		'dd': s => number.padding(date.getDate(), 2, '0'),
 
		'H': s => date.getHours().toString(),
		'HH': s => number.padding(date.getHours(), 2, '0'),
 
		'm': s => date.getMinutes().toString(),
		'mm': s => number.padding(date.getMinutes(), 2, '0'),
 
		's': s => date.getSeconds().toString(),
		'ss': s => number.padding(date.getSeconds(), 2, '0'),
	};
 
	return format.replace(
		/((y{1,5})|(M{1,2})|(d{1,2})|(H{1,2})|(m{1,2})|(s{1,2}))/g,
		m => {
			return map[m](m);
		}
	);
}