jmease
jmease

Reputation: 2535

C# DateTime to String Issue

I feel like this is something I've done a thousand times so not sure why it is being so difficult now. I've created a method that simply returns Today's date for the user based on their UTC offset. But instead of returning a string resembling a date, it is returning this garbage

"䙭/䙭/Ἰ뻱䙭"

Here is the code.

public string getToday(Context context)
{
    var settings = PreferenceManager.GetDefaultSharedPreferences(context);
    var offset = settings.GetInt("offset", -5);
    var now = DateTime.UtcNow.AddHours(offset);

    return now.ToShortDateString();
}

When I step into the code using a breakpoint, offset and now both seem correct. now contains valid date parts all appearing to be accurate. Something about converting now to a string seems to go horribly wrong. Also tried:

return now.ToString("MM/dd/yyyy");

Same result. Weird part is the below code in another activity works without issue

var offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
var now = DateTime.UtcNow.AddHours(offset);
now.ToString("MM-dd-yyyy")

Upvotes: 5

Views: 1732

Answers (2)

Douglas
Douglas

Reputation: 54887

I assume that your device is set to a Chinese/Japanese/Korean culture. If you always want to return US dates, use:

return now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

Edit: Given the rest of your comments, I’m starting to suspect that this might be caused by corruption, or by a bug in the MonoDroid implementation. You could try working around it by constructing the date manually (although this admittedly doesn’t address the cause of your issue):

return string.Format("{0:00}/{1:00}/{2:0000}", now.Month, now.Day, now.Year);

Upvotes: 1

Zenexer
Zenexer

Reputation: 19611

Sounds to me like a localization issue. Make sure you're actually in English, be it en-US or similar.

Upvotes: 3

Related Questions