Machineboy空
C# DateTime 시간, 날짜 다루기 - DateTime.Parse(), TimeSpan.FromSecond(), DateTime.Add(), DayOfWeek 본문
언어/C#
C# DateTime 시간, 날짜 다루기 - DateTime.Parse(), TimeSpan.FromSecond(), DateTime.Add(), DayOfWeek
안녕도라 2025. 1. 17. 13:43DateTime
immutable(불변의) object that contains both date and time information.
DateTime 특징
- 한 번 DateTime이 생성되면 값이 절대 변하지 않는다. DateTime을 modify하려고 하면 return new DateTime
- textual representaion은 dependent on the culture
- en-US(America English) : "3/28/19 2:30:59 PM"
DateTime.Parse() : string을 DateTime으로 변환
using System;
static class Appointment
{
// string -> DateTime
public static DateTime Schedule(string appointmentDateDescription)
{
return DateTime.Parse(appointmentDateDescription);
}
// DateTime.Now
public static bool HasPassed(DateTime appointmentDate)
{
// DateTime이 과거인지
if(DateTime.Now > appointmentDate){
return true;
}else{
return false;
}
}
// DateTime.Hour
public static bool IsAfternoonAppointment(DateTime appointmentDate)
{
// 오후(12시 이후 18시 미만)인지
if(appointmentDate.Hour >= 12 && appointmentDate.Hour < 18){
return true;
}else{
return false;
}
}
// DateTime -> String 변환
public static string Description(DateTime appointmentDate)
{
return $"You have an appointment on {appointmentDate}.";
}
public static DateTime AnniversaryDate()
{
// 2019/9/15 일을 반환하라
return new DateTime(2025,9,15,0,0,0);
}
}
TimeSpan.FromSeconds()
DateTime.Add()
using System;
public static class Gigasecond
{
// 1 gigasecond = 1000000000 seconds
//born in 2015/01/24 22:00
// + 1 gigasecond
//2046/10/02 11:46:40pm
// 1000000000 seconds
// 16,666,666 minutes 40 seconds
// 277,777 hours 46 minutes 40 seconds
// 11,574 days 1 hours 46 minutes 40 seconds
//
public static DateTime Add(DateTime moment)
{
TimeSpan gigasecond = TimeSpan.FromSeconds(1_000_000_000);
return moment.Add(gigasecond);
}
}
using System;
public static class Gigasecond
{
public static DateTime Add(DateTime birthDate) => birthDate.AddSeconds(1e9);
}
DateTime생성 및 DayOfWeek
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime targetDate;
case Schedule.Teenth:
for (int day = 13; day <= 19; day++)
{
targetDate = new DateTime(year, month, day);
// DayOfWeek(요일)
if (targetDate.DayOfWeek == dayOfWeek)
return targetDate;
}
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime targetDate;
case Schedule.First:
targetDate = firstDayOfMonth;
while (targetDate.DayOfWeek != dayOfWeek)
targetDate = targetDate.AddDays(1);
return targetDate;
https://exercism.org/tracks/csharp/exercises/meetup/iterations
'언어 > C#' 카테고리의 다른 글
Visual Studio 기본 환경 세팅 (0) | 2025.01.23 |
---|---|
C# Class: static Field 정적 필드, 클래스와 인스턴스 (0) | 2025.01.20 |
C# Class 기초,필드, 메소드, 멤버, 접근자, 생성자, 예제 등 (0) | 2025.01.16 |
C# if문, switch문, for문, forEach문, while문 (0) | 2025.01.16 |
C# 컬렉션 - 배열, 다차원 배열 - rank, getLength, Array.IndexOf(), Array.Sort() (0) | 2025.01.15 |