Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

DateTime.Parse returns wrong value when CultureInfo is used

This is my code:

DateTime Now = DateTime.Parse(DateTime.Now.ToString(), new System.Globalization.CultureInfo("fa-ir"));

The Geogorian date is: 16/06/2016

The Persian date is: 15/03/1395

while the value of Now is: 07/09/2025

The time is correct. What can be the problem?

Upvotes: 1

Views: 1108

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503469

If you're trying to obtain the year, month and day of "now" in the Persian Calendar, you should use the Calendar class:

using System;
using System.Globalization;

public class Test
{
    static void Main()
    {
        var now = DateTime.Now;
        var calendar = new PersianCalendar();
        Console.WriteLine($"Year: {calendar.GetYear(now)}");
        Console.WriteLine($"Month: {calendar.GetMonth(now)}");
        Console.WriteLine($"Day: {calendar.GetDayOfMonth(now)}");
    }
}

If you just want to format a value as a string, you can pass the CultureInfo into the ToString call:

using System;
using System.Globalization;

public class Test
{
    static void Main()
    {
        var culture = new CultureInfo("fa-ir");
        var now = DateTime.Now;
        Console.WriteLine(now.ToString(culture));
    }
}

Here, the CultureInfo has a default calendar associated with it (as well as date/time format strings) and that is used to format the value.

A DateTime itself is always effectively in the Gregorian calendar system - there's no way of creating a "DateTime in the Persian Calendar" for example, or "converting" a DateTime from one calendar to another.

Note that in my Noda Time library, that's not true - you can specify a calendar system for a ZonedDateTime, OffsetDateTime, LocalDate or LocalDateTime value, and convert from one to another. If you're doing a lot of calendar work, I'd recommend you at least give Noda Time a try - it's designed to make it a lot harder to make this sort of mistake.

Upvotes: 1

KristoferA
KristoferA

Reputation: 12397

You are only passing a cultureinfo param to Parse, but not to ToString. This means the string is formatted using the thread culture, and then parsed using fa-ir culture.

Upvotes: 5

Related Questions