Convert DateTime with a specified language - datetime

I am coding a MVC 5 internet application and am wanting to convert a DateTime to be displayed as a LocalTime where I have the language. This is for an Azure website.
Here is my code:
DateTime dateTimeUtcNow = DateTime.UtcNow;
DateTime convertedDate = DateTime.SpecifyKind(dateTimeUtcNow, DateTimeKind.Utc);
DateTime dateTimeLocalTime = convertedDate.ToLocalTime();
return dateTimeLocalTime.ToString(new CultureInfo("en-NZ"));
The output from the above code is the exact same output as if I return the DateTime in UTC with no language culture specified.
How can I convert a DateTime in UTC for a local time where I have the culture language?
Thanks in advance.

You can use the second argument to the toString function and use any language/culture you need...
You can use the "d" format instead of ToShortDateString according to MSDN...
So basically something like this to return as NewZ ealand English:
CultureInfo enAU = new CultureInfo("en-NZ");
dt.ToString("d", enAU);
you could modify your method to include the language and culture as a parameter
public static string ConvertDateTimeToDate(string dateTimeString, String langCulture) {
CultureInfo culture = new CultureInfo(langCulture);
DateTime dt = DateTime.MinValue;
if (DateTime.TryParse(dateTimeString, out dt))
{
return dt.ToString("d",culture);
}
return dateTimeString;
}
You may also want to look at the overloaded tryParse method if you need to parse the string against a particular language/culture...

Related

Comparing two datetime

I send a datetime using query $post to Mvc Controller;
1- On the server machine it doesn't bind well , some time in wrong format
I solved it by sending datetime as string then split the string to day, month , year.
2- Second problem; I parsed the datetime but when I compare it with another one it gives me wrong result.
Post your date/time formatted in the ISO standard.
var myDate = new Date();
var dateString = myDate.toISOString();
Post dateString to your api.

JSON date to asp.net DateTime is changed at runtime

I've searched around and I'm really not sure why this happens.
Most of the time my app runs in GMT from devices using GMT, but I just span a server up in Singapore, so the time is 8hrs ahead. I'm seeing some strange behaviour with DateTime objects parsed from JSON:
My app received a JSON (ISO 8601) date like this:
LastSync=2013-01-10T11:05:38.822Z
I'm using a simple .asmx web-service, that uses the built in JSON serializer for .Net 3.5, the automatically parsed DateTime object returns a date 8hrs ahead of what the JSON says it should be. Here's the function:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function SyncFlatTable(ByVal tableName As String, ByVal LastSync As DateTime)
Return WebServiceJSON.SyncFlatTable(tableName, LastSync)
End Function
As you can see the LastSync as DateTime argument's value is 8hrs ahead:
The weird thing is if I return Now(), the JSON output from the web service is:
newLastSend=/Date(1357817197087)/
Which using a timestamp to date online converter is no-longer 8hrs ahead.
Is this IIS's fault? I can't see any other culture settings everything else is neutral, why would it change the date? How do I stop it, or do I have to take what I'm given and adjust the date to an invariant culture date?
I got this problem as well, I ended up using the sting type to pass in/out the date info.
It seems that calling .toJSON on any date object, when it's converted to a string representation it is done so using a local date. I needed to adjust this to UTC so that when it's converted it does so with what the date should be for the server:
function removeDateUTCOffSetForServer(obj) {
if (obj) {
for (prop in obj) {
if (obj[prop] instanceof Date) {
var d = obj[prop];
var utc = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
obj[prop] = utc;
}
}
}
return obj;
}

Converting any date format in MM/DD/YYYY format

I am having difficulty with different date formats. I am having a web application created using asp.net c#. I have used JQuery Calendar control which shows date along-with time.
I am then parsing this date using DateTime.Parse(). If the server is set with indian date format then the application generates conversion error "String was not recognized as a valid DateTime."
Is there a way to convert any date format into MM/DD/YYYY format along with time?
I know i can use DateTime.ParseExact() but again it will stuck with a particular format.
Any help is greatly appreciated.
Thanks for sharing you wisdom.
Convert.ToDateTime(DateTime.Now, CultureInfo.GetCultureInfo("en-US")).ToString("MM/dd/yyyy hh:MM:ss");
You can replace en-US by hi-IN for Hindi Date or as per you like. please follow link. for Culture Info.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
If you are unsure of Culture then use below line.
Convert.ToDateTime(DateTime.Now, CultureInfo.CurrentCulture).ToString("MM/dd/yyyy hh:MM:ss");
reference here http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx
Other Method you can use is.
DateTime dt;
DateTime.TryParse(DateTime.Now.ToString(), out dt);
You can try DateTime.Parse or DateTime.TryParse methods
DateTime.Parse(DateTime.Now).ToString("MM/dd/yyyy hh:mm tt");
Also refer
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Thanks
Deepu
You can create an Extension methods for this you need to create a static class with static method. It will return you a date format that you define in class
public static class DateExtension
{
public static string GetDateTime(this DateTime? date)
{
if (date.HasValue)
return date.Value.ToString("dd-MMM-yyyy hh:mm tt");
return string.Empty;
}
}
Now in you code you can use this extension for e.g. DateTime.GetDateTime() it will return date with time that with the format you specify in your extension library class
string s;
s = dt.ToString("MM-dd-yyyy");
Console.WriteLine(s);//Displays 04-30-2012
You can use this code.
public static CultureInfo CreateCulture(string shortDateFormat)
{
CultureInfo newCulture = CultureInfo.CreateSpecificCulture("en-US");
newCulture.DateTimeFormat.ShortDatePattern = shortDateFormat;
newCulture.DateTimeFormat.LongDatePattern = shortDateFormat;
return newCulture;
}

showing DateTime in simple format?

i have a column in my database that stores DateTime, now i want to show time in simple format,
you know it will appear like : 12/26/2011 9:39:55 PM
but i want to show it in persian.
When you want to format the DateTime in your application, you need to use a DateTime.ToString overload.
Select the appropriate standard Date and Time format string - in this case "g" looks like a good fit.
If you have not set up your webserver to use the fa-IR culture by default, you will need to pass this culture in as well.
string farsiDate = myDateTime.ToString("g", CultureInfo.GetCultureInfo("fa-IR");
Have a look at the examples on MSDN for using the PersianCalendar class.
var cal = new PersianCalendar();
var today = DateTime.Now;
var persianDate = string.Format("{0}/{1}/{2}",
cal.GetDayOfMonth(today),
cal.GetMonth(today),
cal.GetYear(today));

ASP.NET Change Culture for ONLY Currency not date, etc

I have a base class that inherits a page and changes the culture based on a pre-determined value set in the database. I need the culture to change the currency symbol but nothing else. If the value in the db says en-GB I need for it to change all currency values on the page to British pounds, and if it sais en-US show a US Dollar Sign. I need the culture variable to only effect the currency and nothing else, all dates, etc should be in the default culture(en-US)
Any ideas?
Basically you need to use a format provider when formatting your numbers as currency. Have a look at the following example:
public static string CulturedCurrency(decimal number,string culture = "en-US")
{
NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture(culture).NumberFormat;
return number.ToString("c",numberInfo);
}
Reference: http://geekswithblogs.net/dtotzke/articles/24573.aspx
If you want to do it inline on databinding have a look at the code here: Format string by CultureInfo
I have found the solution I was looking for. Going through and changing each element of currency to use the specified culture was not something that would be easily done so I started playing with other options and what I have found was that if I used the culture function in my base class I could do the following:
System.Globalization.CultureInfo ci;
if (culture == "")
{
ci = new System.Globalization.CultureInfo("en-US");
}
else
{
ci = new System.Globalization.CultureInfo(culture);
}
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
ci.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
ci.DateTimeFormat.LongDatePattern = "dddd, MMMM dd, yyyy";
ci.DateTimeFormat.DateSeparator = "/";
This will set the culture to what I want and then set the date of the culture (no matter what the culture is) to the US Format of the datetime. Thanks for all the help!
Most ToString methods take a format provider; the Culture Info is a format provider. You are going to have to leave the current culture as en-US and manually format the currency values using the ToString() method.
http://msdn.microsoft.com/en-us/library/3ebe5aks.aspx
HTH.
using System.Globalization;
...
value.ToString(CultureInfo.CreateSpecificCulture("en-US"));
A little add on Rob's answer, if you have a localization attribute in your URL, and thus setting the Culture on every request, you might just want to do it like this:
//get language attribute from url. (requires special routing in MVC)
string lang = (string)filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
switch (lang)
{
case "nl":
lang = "nl-NL";
break;
case "en":
lang = "en-GB";
break;
case "en-US":
lang = "en-US";
break;
default:
lang = _DefaultLanguage;//nl-NL
break;
}
NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture("nl-NL").NumberFormat; //always use euros as currency
CultureInfo info = new CultureInfo(lang);
info.NumberFormat = numberInfo;

Resources