0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プログラミング・スキルチェック問題「日付データの変換」ランクC

Last updated at Posted at 2019-03-11

はじめに

パイザ・スキルチェックの問題が"自由"に使えないので、学習者向け問題を自作してみました。なお、この問題はGNU GPLです。"自由"にご使用ください。

問題

西暦日付(ハイフン区切り)が、入力として与えられます。

これを西暦日付(スラッシュ区切り)で出力してください。

例)2019-04-01 → 2019/04/01

なお、入力が西暦日付(ハイフン区切り)の形式ではない時は、Falseを出力してください。

入力される値

1行目には西暦日付(ハイフン区切り)の文字列"Y/M/D"が入力されます。

期待する出力

西暦日付(ハイフン区切り)ならば西暦日付(スラッシュ区切り)、違う場合はFalseを出力してください。

条件

文字Yは、0000~9999
文字Mは、01~12
文字Dは、01~31

※前ゼロの有無と存在しない日付(2/31など)については問題が難しくなるため、考慮してもしなくてもかまいません(回答の成否に影響しないものとします)

入力例1

2019-03-23

出力例1

2019/03/23

入力例2

2019.03.23

出力例2

Flase

回答例

python3の例

python3.py
# coding: utf-8
# Your code here!
import sys

line = input().split("-")

# 要素数チェック
if len(line) != 3:
    print("False")
    sys.exit()

flg = 0

for x in line:
    if not x.isdigit():
        print("False")
        sys.exit()

if not (int(line[0]) >= 0 and int(line[0]) <= 9999):
    print("False")
    sys.exit()

if not (int(line[1]) >= 1 and int(line[1]) <= 12):
    print("False")
    sys.exit()

if not (int(line[2]) >= 1 and int(line[2]) <= 31):
    print("False")
    sys.exit()

print(line[0].zfill(4) + "/" + line[1].zfill(2) + "/" + line[2].zfill(2))

PHPの例

php7.php
<?php
$date = trim(fgets(STDIN));

if( ! preg_match('/^([0-9]{1,4})\-(0[1-9]{1}|[1-9]{1}|1[0-2]{1})\-(0[1-9]{1}|[1-9]{1}|[1-2]{1}[0-9]{1}|3[0-1]{1})$/', $date)){
    echo "False";
    exit;
}

// 前ゼロいれないと正しく出力されない…
$date = explode("-", $date);
$date = sprintf('%04d', $date[0]). sprintf('%02d', $date[1]). sprintf('%02d', $date[2]);

$obj = new DateTime($date);
echo $obj->format('Y/m/d');

参考にしたサイト

お願い

誤りやスマートな回答方法など、お気づきの点があればぜひ教えてくださいm(_ _)m

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?