본문 바로가기
기타

[ASP.NET Core/APOD] 게시 후와 게시 전의 DateTime.Now 값이 다른 문제

by 항붕쿤 2023. 4. 19.

DateTime.Now는 현재 시스템 날짜와 시간을 가져오는 함수이다. 로컬 컴퓨터에서 DateTime.Now를 호출하면 로컬 컴퓨터의 현재 시간이 반환되지만, Azure 서버에서 호출하면 Azure 서버가 위치한 시간대의 현재 시간이 반환되어다. 게시 후와 게시 전의 DateTime.Now 값이 달라지게된다.

게시 전과 후

이러한 문제는 UTC 시간을 사용함으로써 해결할 수 있다.
DateTime.UtcNow를 사용하여 UTC 시간을 가져올 수 있으며, TimeZoneInfo.ConvertTimeFromUtc 함수를 사용하여 로컬 시간으로 변환할 수 있다.

[HttpPost]
public async Task<IActionResult> Details(int id, [Bind("APOD,New_Comment,Comment")] APODAndCommentViewModel commentModel)
{
    DateTime utcNow = DateTime.UtcNow;
    TimeZoneInfo kst = TimeZoneInfo.FindSystemTimeZoneById("Korea Standard Time");
    DateTime kstNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, kst);

    commentModel.New_Comment.Date = kstNow;
    commentModel.New_Comment.PostId = id;

    _context.CommentModel.Add(commentModel.New_Comment);

    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Details), new { id = commentModel.New_Comment.PostId });
}

실행결과

잘 작동한다