[백준 16170] 오늘의 날짜는? (C#, C++) - soo:bak
작성일 :
문제 링크
설명
프로그램이 실행되는 시점의 UTC+0 기준 날짜를 출력하는 문제입니다.
연도, 월, 일을 각각 한 줄씩 출력하며, 월과 일은 두 자리 숫자로 출력해야 합니다.
접근법
채점 서버에서 실행되는 현재 시간을 사용해야 하므로, 시스템의 UTC 시간을 읽어야 합니다.
C#의 경우 DateTime.UtcNow를 사용하여 현재 UTC 시간을 얻습니다. 연도는 Year 속성으로, 월과 일은 ToString("MM"), ToString("dd")로 두 자리 형식을 보장하며 출력합니다.
C++의 경우 time() 함수로 현재 시간을 얻고, gmtime()으로 UTC 시간 구조체로 변환합니다.
tm_year는 1900년부터의 경과 연수이므로 1900을 더해야 하고, tm_mon은 0부터 시작하므로 1을 더해야 합니다.
월과 일은 setw(2)와 setfill('0')을 사용하여 두 자리로 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
namespace Solution {
class Program {
static void Main(string[] args) {
var utc = DateTime.UtcNow;
Console.WriteLine(utc.Year);
Console.WriteLine(utc.ToString("MM"));
Console.WriteLine(utc.ToString("dd"));
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
time_t now = time(nullptr);
tm* utc = gmtime(&now);
cout << (utc->tm_year + 1900) << "\n";
cout << setw(2) << setfill('0') << (utc->tm_mon + 1) << "\n";
cout << setw(2) << setfill('0') << utc->tm_mday << "\n";
return 0;
}