C#中按指定时区显示特定格式DateTime及获取对应文化码
Great question! Let's break this down step by step. The short answer: Yes, you can map a time zone to a corresponding culture code, but keep in mind time zones and cultures aren't strictly one-to-one—one time zone might be used by multiple cultures. You'll need to handle that ambiguity based on your business needs.
Let's solve your specific scenario: taking a datetime like 24-02-2018 07:30:00, parsing/displaying it in either DD-MM-YY or MM-DD-YY format based on the target time zone, and integrating this into your email's "Last Updated" field.
Step 1: Convert the DateTime to the Target Time Zone
First, make sure you're working with a datetime that has clear time zone context (preferably UTC to avoid confusion). Convert it to your target time zone using TimeZoneInfo:
// Example: Original UTC datetime (adjust if your source time is in a different zone) DateTime utcDateTime = new DateTime(2018, 2, 24, 7, 30, 0, DateTimeKind.Utc); // Target time zone ID (replace with your actual zone, e.g., "Eastern Standard Time" or "GMT Standard Time") string targetTimeZoneId = "GMT Standard Time"; TimeZoneInfo targetTimeZone = TimeZoneInfo.FindSystemTimeZoneById(targetTimeZoneId); // Convert UTC time to the target time zone DateTime targetDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, targetTimeZone);
Step 2: Map Time Zone to a CultureInfo
A single time zone can be used by multiple cultures (e.g., Eastern Standard Time is used by en-US, es-US, fr-CA). Here's a method to fetch a relevant culture for your time zone, with priority logic to handle ambiguity:
public static CultureInfo GetCultureForTimeZone(string timeZoneId) { TimeZoneInfo targetTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); // Filter all specific cultures to find those using the target time zone var matchingCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures) .Where(culture => { try { var cultureTimeZone = TimeZoneInfo.FindSystemTimeZoneById(culture.DateTimeFormat.TimeZoneId); return cultureTimeZone.Id == targetTimeZone.Id; } catch (TimeZoneNotFoundException) { // Skip cultures with invalid time zone mappings return false; } }) .ToList(); if (!matchingCultures.Any()) { // Fallback to a default culture if no matches are found return CultureInfo.InvariantCulture; // Or throw an exception if required: // throw new InvalidOperationException($"No culture found for time zone: {timeZoneId}"); } // Prioritize a culture that fits your business needs (e.g., English-speaking cultures first) return matchingCultures.FirstOrDefault(c => c.Name.StartsWith("en")) ?? matchingCultures.First(); }
Step 3: Format the DateTime for the Target Culture
Once you have the correct CultureInfo, format the datetime to match the culture's standard pattern, or enforce DD-MM-YY/MM-DD-YY explicitly:
CultureInfo targetCulture = GetCultureForTimeZone(targetTimeZoneId); string formattedDate; // Check the culture's short date pattern to decide the format if (targetCulture.DateTimeFormat.ShortDatePattern.Contains("dd/MM/yy")) { formattedDate = targetDateTime.ToString("dd-MM-yy", targetCulture); } else if (targetCulture.DateTimeFormat.ShortDatePattern.Contains("MM/dd/yy")) { formattedDate = targetDateTime.ToString("MM-dd-yy", targetCulture); } else { // Fallback to a default format if the culture uses something else formattedDate = targetDateTime.ToString("dd-MM-yy", targetCulture); } // Combine with time for your email field string lastUpdatedText = $"最后更新时间:{formattedDate} {targetDateTime.ToString("HH:mm:ss", targetCulture)}"; Console.WriteLine(lastUpdatedText);
Key Notes to Avoid Issues
- DateTime Kind Matters: Always ensure your source datetime has the correct
DateTimeKind(Utc, Local, or Unspecified). Using UTC as your base avoids daylight saving time and offset errors. - One-to-Many Ambiguity: If a time zone maps to multiple cultures, adjust the
GetCultureForTimeZonemethod to prioritize the culture that makes sense for your users (e.g., use the user's preferred language if available). - Fallback Logic: Have a fallback culture (like
CultureInfo.InvariantCulture) in case no matching culture is found for a time zone.
内容的提问来源于stack exchange,提问作者DevPerson

