IRONSOFTWAREHOME
개발자 업데이트

C#의 DateTime 객체 (개발자를 위한 작동 원리)

제이콥 멜러, 팀 아이언 최고기술책임자
Jacob Mellor
Updated: 2026년 4월 23일

DateTime 개체는 C#에서 .NET Framework 애플리케이션에서 날짜와 시간을 다루기 위한 기본 요소입니다. 이들은 날짜와 시간을 조작, 형식 지정 및 비교하는 강력한 기능 세트를 제공합니다.

이 기사는 C#의 DateTime 개체에 대한 포괄적인 개요를 제공하며, 생성, 조작, 형식 지정 및 일반적인 사용 사례를 다룹니다. 기사의 마지막 부분에서는 IronPDFIron Software에서 C# 애플리케이션 내부에서 어떻게 PDF 문서를 즉석에서 생성할 수 있는지도 살펴봅니다.

DateTime 객체 생성하기

C#에서 DateTime 개체를 생성하는 것은 간단합니다. 다양한 매개변수를 사용하여 DateTime 개체를 초기화할 수 있는 여러 생성자가 있습니다:

// Current date and time
DateTime currentDateTime = DateTime.Now;
// Specific date and time
DateTime specificDateTime = new DateTime(2024, 3, 16, 10, 30, 0);
// Date only
DateTime dateOnly = DateTime.Today;
// Date and time in UTC
DateTime utcDateTime = DateTime.UtcNow;

DateTime 개체 조작

날짜 및 시간을 조작하기 위한 다양한 메소드를 제공하여 시간 간격을 추가하거나 빼고, 구성 요소를 추출하고, 시간대 간 변환을 수행할 수 있습니다.

DateTime now = DateTime.Now;
// Adding days
DateTime futureDate = now.AddDays(7);
// Subtracting hours
DateTime pastTime = now.AddHours(-3);
// Getting components
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
// Converting between time zones
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = utcTime.ToLocalTime();

DateTime 개체 형식 지정

DateTime 개체는 요구되는 형식으로 표현되도록 다양한 형식 지정자을 사용하여 문자열로 형식화될 수 있습니다.

DateTime dateTime = DateTime.Now;
// Standard date and time format
string standardFormat = dateTime.ToString("G");
// Custom format
string customFormat = dateTime.ToString("dd/MM/yyyy HH:mm:ss");
// Format for sorting
string sortableFormat = dateTime.ToString("yyyy-MM-ddTHH:mm:ss");

DateTime 개체 비교

C#은 두 DateTime 개체를 직접 비교할 수 있는 표준 비교 연산자 (<, >, <=, >=, ==, !=)를 제공합니다. 이 연산자들은 그레고리력 기준 0001년 1월 1일 00:00:00.000 이후 경과한 100나노초 간격의 수를 나타내는 DateTime 개체의 기본 틱을 비교합니다.

다음은 비교 연산자의 사용 예제입니다:

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
if (date1 < date2)
{
    Console.WriteLine("date1 is earlier than date2.");
}
else if (date1 > date2)
{
    Console.WriteLine("date1 is later than date2.");
}
else
{
    Console.WriteLine("date1 is equal to date2.");
}

DateTime.Compare C# 메소드 사용

비교 연산자 외에도 DateTime 개체는 해당 개체 간의 상대적인 값을 비교하는 메소드를 제공합니다. 이 메서드는 특정 시나리오에서 더 많은 유연성과 가독성을 제공합니다. CompareTo() 메소드는 두 DateTime 개체를 비교하고, 하나가 다른 하나보다 이른지, 늦은지 혹은 같은지를 나타내는 정수 값을 반환합니다.

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
int result = date1.CompareTo(date2);
if (result < 0)
{
    Console.WriteLine("date1 is earlier than date2.");
}
else if (result > 0)
{
    Console.WriteLine("date1 is later than date2.");
}
else
{
    Console.WriteLine("date1 is equal to date2.");
}

허용 오차를 가진 DateTime 개체 비교

DateTime 개체를 비교할 때, 특히 시간 간격을 포함하는 계산을 다룰 경우, 허용 오차 수준을 고려하는 것이 중요합니다.

이는 두 DateTime 값 사이의 절대 차이를 사전 정의된 허용 오차 임계값과 비교함으로써 달성할 수 있습니다.

class Program
{
    public static void Main()
    {
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddMilliseconds(10);
        TimeSpan tolerance = TimeSpan.FromMilliseconds(5);
        bool isEqual = Math.Abs((date1 - date2).TotalMilliseconds) <= tolerance.TotalMilliseconds;
        if (isEqual)
        {
            Console.WriteLine("date1 is considered equal to date2 within the tolerance.");
        }
        else
        {
            Console.WriteLine("date1 is not equal to date2 within the tolerance.");
        }
    }
}

시간대 및 일광 절약 시간제 처리하기

C#의 DateTime 개체는 지역 시간과 협정 세계시(UTC)를 모두 나타낼 수 있습니다. 특히 글로벌 애플리케이션을 다룰 때는 시간대 변환에 유의하는 것이 중요합니다.

DateTime localTime = DateTime.Now;
DateTime utcTime = DateTime.UtcNow;
Console.WriteLine("Local Time: " + localTime);
Console.WriteLine("UTC Time: " + utcTime);

IronPDF to Generate PDF documents in C#

Iron Software의 IronPDF는 효율적이고 사용하기 쉬운 PDF 생성 라이브러리입니다. NuGet 패키지 관리자를 사용하여 설치할 수 있습니다:

 C#의 날짜 시간 개체 (개발자에게 어떻게 작용하는지): 그림 1

dotnet add package IronPdf --version 2024.3.4

또는 아래에 표시된 대로 Visual Studio에서 설치할 수 있습니다:

 C#의 날짜 시간 개체 (개발자에게 어떻게 작용하는지): 그림 2 - NuGet 패키지 관리자를 사용한 IronPDF 설치

이제 PDF 생성을 탐구하여 DateTime 객체를 시연해봅시다.

using IronPdf;

class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        
        // Create a new instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();
        
        // HTML content for the PDF
        var content = "<h1> Iron Software is Awesome </h1> Made with IronPDF!";
        content += "<h2>Demo Datetime Objects in C#</h2>";
        
        // Current date and time
        content += "<h3>Current date and time</h3>";
        DateTime currentDateTime = DateTime.Now;
        content += $"<p>Current date and time: {currentDateTime:U}</p>";
        Console.WriteLine($"Current date and time: {currentDateTime:U}");
        
        // Specific date and time
        content += "<h3>Specific date and time</h3>";
        DateTime specificDateTime = new DateTime(2024, 3, 16, 10, 30, 0);
        content += $"<p>Specific date and time: {specificDateTime:U}</p>";
        Console.WriteLine($"Specific date and time: {specificDateTime:U}");
        
        // Date only
        content += "<h3>Date Only</h3>";
        DateTime dateOnly = DateTime.Today;
        content += $"<p>Date only: {dateOnly:U}</p>";
        Console.WriteLine($"Date only: {dateOnly:U}");
        
        // Date and time in UTC
        content += "<h3>Date and time in UTC</h3>";
        DateTime utcDateTime = DateTime.UtcNow;
        content += $"<p>Date and time in UTC: {utcDateTime:U}</p>";
        Console.WriteLine($"Date and time in UTC: {utcDateTime:U}");
        
        // Compare dates with Operators
        content += "<h3>Compare dates with Operators</h3>";
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddDays(1);
        content += $"<p>Compare date1 {date1:d}, date2 {date2:d}: {CompareDates(date1, date2)}</p>";
        Console.WriteLine($"Compare date1 {date1:U}, date2 {date2:U}: {CompareDates(date1, date2)}");
        
        // Compare dates with Compare Method
        content += "<h3>Compare dates with Compare Method</h3>";
        content += $"<p>Compare date1 {date1:d}, date2 {date2:d}: {CompareDatesWithCompare(date1, date2)}</p>";
        Console.WriteLine($"Compare date1 {date1:U}, date2 {date2:U}: {CompareDatesWithCompare(date1, date2)}");
        
        // Render the content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        
        // Save the PDF to the output file
        pdf.SaveAs("outputDate.pdf");
    }
    
    // Compare two dates using CompareTo method
    public static string CompareDatesWithCompare(DateTime date1, DateTime date2)
    {
        int result = date1.CompareTo(date2);
        string resultString;
        if (result < 0)
        {
            resultString = "date1 is earlier than date2.";
            Console.WriteLine(resultString);
        }
        else if (result > 0)
        {
            resultString = "date1 is later than date2.";
            Console.WriteLine(resultString);
        }
        else
        {
            resultString = "date1 is equal to date2.";
            Console.WriteLine(resultString);
        }
        return resultString;
    }
    
    // Compare two dates using basic comparison operators
    public static string CompareDates(DateTime date1, DateTime date2)
    {
        string result;
        if (CheckLessor(date1, date2))
        {
            result = "date1 is earlier than date2.";
            Console.WriteLine(result);
        }
        else if (CheckGreater(date1, date2))
        {
            result = "date1 is later than date2.";
            Console.WriteLine(result);
        }
        else
        {
            result = "date1 is equal to date2.";
            Console.WriteLine(result);
        }
        return result;
    }
    
    // Helper method to check if the first date is greater than the second date
    public static bool CheckGreater(DateTime date1, DateTime date2)
    {
        return date1 > date2;
    }
    
    // Helper method to check if the first date is less than the second date
    public static bool CheckLessor(DateTime date1, DateTime date2)
    {
        return date1 < date2;
    }
}

다음 출력은 DateTime 개체로 생성된 PDF를 보여줍니다:

DateTime C#의 날짜 시간 개체 (개발자에게 어떻게 작용하는지): 그림 3

IronPDF 체험판 라이선스

IronPDF는 전체 기능 사용을 위해 체험판 라이선스를 요구합니다. 라이선스 키를 생성하여 이메일로 전달 받기 위해 이메일 ID를 제공하십시오.

"IronPdf.LicenseKey": "<Your Key>"
JSON

라이선스 키를 AppSettings.json 파일에 위치시키세요.

결론

C#의 DateTime 개체는 .NET 애플리케이션에서 날짜와 시간을 다루는 강력한 방법을 제공합니다. 이들은 날짜 및 시간 값 생성, 조작, 형식 지정 및 비교를 위한 다양한 기능을 제공합니다. DateTime 개체를 효과적으로 사용하는 방법을 이해하는 것은 C# 애플리케이션에서 신뢰할 수 있고 정확한 날짜 및 시간 기능을 구축하기 위해 필수적입니다.

DateTime 개체의 기능을 활용함으로써, 개발자는 애플리케이션이 특정 요구 사항 또는 시나리오에 관계없이 날짜와 시간을 올바르게 처리할 수 있도록 보장할 수 있습니다.

기간 계산, 작업 일정 계획 또는 사용자에게 날짜와 시간을 표시하는 등 DateTime 개체는 C# 프로그래밍에서 날짜 및 시간 관리와 관련된 많은 측면에서 중요한 역할을 합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

...
더 읽어보기

관련 기사

Key in blue circle

무료 30일 체험 키를 즉시 받으세요.

Your trial license will be sent to your email address

제한 없음. 100% 무제한 이용. 신용카드 불필요.

bullet_checked신용카드나 계정 생성은 필요하지 않습니다.제한 없음. 100% 무제한 이용. 신용카드 불필요.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
무료 라이브 데모를 예약하세요
Booking Badge

전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.

Iron Software의 고객 로고
부담 없는 무료 상담을 받아보세요
아래 양식을 작성하시거나 sales@ironsoftware.com으로 이메일을 보내주세요.
고객님의 정보는 항상 비밀로 유지됩니다.
전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.
Iron Software의 고객 로고
지금 바로 30일 무료 체험판 키를 받으세요.
신용카드나 계정 생성은 필요하지 않습니다.