What is the alternative in C# [duplicate] - c#

This question already has answers here:
Format string by CultureInfo
(5 answers)
Closed 8 years ago.
I found how to change the locale format in Java, but I want to use it in C#.
This is the (Java) line of code
String.format(Locale.US, "%f", floatValue)

For Culture you can Use
CultureInfo en = new CultureInfo("en-US");
and for Formatting Float with Culture you can use
string.Format(new System.Globalization.CultureInfo("en-Us"), "{N2}", floatValue)

C# equivalent is (simple to string conversion)
String result = floatValue.ToString(new CultureInfo("en-US"));
Or (formatting)
String result = String.Format(new CultureInfo("en-US"), "{0}", floatValue);

By default in .Net if you use CultureInfo.InvariantCulture it is associated with the English language en-US
or you can explicitly set CUltureInfo
float value = 16325.62015;
// Display value using the invariant culture.
Console.WriteLine( value.ToString(CultureInfo.InvariantCulture));
// Display value using the en-US culture.
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-US")));

Related

DateTime.ParseExact - different outputs on Windows 10 and WinServer2012R2 [duplicate]

This question already has answers here:
Parsing "12/25/35" to a date using InvariantCulture (2-digit year)
(1 answer)
DateTime.ParseExact - why yy turns into 2015 not 1915
(2 answers)
DateTime.TryParse century control C#
(6 answers)
DateTime TryParse - mapping '99' to 2099, not 1999 [duplicate]
(2 answers)
Closed 1 year ago.
I found out that this line:
DateTime.ParseExact("Jan 30", "MMM yy", null, System.Globalization.DateTimeStyles.None)
creates the date:
2030-01-01
...on my Windows 10 machine, but on Windows Server 2012 R2 the output is:
1930-01-01
Does anybody know how to get Windows Server 2012 to parse the date as 2000 instead of 1900?
It's based on the culture's default calendar's TwoDigitYearMax property. If you change that property value, you'll get a different result:
using System;
using System.Globalization;
class Program
{
static void Main(string[] args)
{
var culture = CultureInfo.CurrentCulture;
// Clone returns a *mutable* copy.
culture = (CultureInfo) culture.Clone();
culture.DateTimeFormat.Calendar.TwoDigitYearMax = 2029;
var result = DateTime.ParseExact("Jan 30", "MMM yy", culture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(result.Year); // 1930
culture.DateTimeFormat.Calendar.TwoDigitYearMax = 2129;
result = DateTime.ParseExact("Jan 30", "MMM yy", culture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(result.Year); // 2030
}
}

Convert ".1", ".2" to double [duplicate]

This question already has answers here:
double.Parse throw a System.FormatException
(3 answers)
Closed 7 years ago.
I want to convert string like ".1", ".2", etc into 0.1, 0.2 etc.
I tried:
Convert.ToDouble(".1")
and it crashes. I understand why it crashes, but I still need to convert it to valid double number. I know I can do this with splitting string and parsing but is there a better way?
Convert.ToDouble uses current culture settings by default.
Probably your current culture has different string than . as a NumberDecimalSeparator.
As a solution, you can use a culture that already has . as a NumberDecimalSeparator like InvariantCulture, or your can Clone your CurrentCulture, set it's NumberDecimalSeparator to . and use that cloned culture in your Convert.ToDouble method (or double.Parse) as a second parameter.
var d = double.Parse(".1", CultureInfo.InvariantCulture);
or
var clone = (CultureInfo)CultureInfo.CurrentCulture.Clone();
clone.NumberFormat.NumberDecimalSeparator = ".";
var d = double.Parse(".1", clone);
Try this:
Double result = Double.Parse(".1", CultureInfo.InvariantCulture);
by specifing CultureInfo.InvariantCulture you ensure . to be a decimal separator.

Convert(change) current DateTime as per culture in c#

if (!IsPostBack && !Page.IsCallback)
{
double OffsetHrs = GetTimeZoneOffsetFromCookie();
string dateFormat = ServiceManager.LocalizationService.GetString("AppHeaderTop", "DateFormat", "g");
CultureSelected CultureSelected = GetCultureSelected();
ASPxLabelCurrentTime.Text = DateTime.Now.ToUniversalTime().AddHours(-OffsetHrs).ToString(dateFormat);
if (CultureSelected.CultureCode != "en-US")
{
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo currentDtfi = new CultureInfo(CultureSelected.CultureCode, false).DateTimeFormat;
ASPxLabelCurrentTime.Text = Convert.ToDateTime(ASPxLabelCurrentTime.Text, usDtfi).ToString(currentDtfi.ShortDatePattern); //what can i Use here ?
}
Let say Output of ASPxLabelCurrentTime.Text
for en-US culture is 11/2/2015 4:14 PM (70)
If I select specific culture I want this datetime 11/2/2015 4:14 PM (70) to appear in that specific culture format.
Your question seems unclear but I try to give a shot.
First of all, what is this (70) exactly? Where is this came from? en-US culture can't parse this string without using it in a string literal delimiter with ParseExact or TryParseExact methods. On the other hand, since you assing ASPxLabelCurrentTime.Text the result of the DateTime.Now.ToUniversalTime().AddHours(-OffsetHrs).ToString(dateFormat) code, I don't believe this (70) part is really an issue on this question.
Second, If I understand clearly, the problem seems the usage of DateTime.ToString(string) method.
ASPxLabelCurrentTime.Text = Convert.ToDateTime(ASPxLabelCurrentTime.Text, usDtfi)
.ToString(currentDtfi.ShortDatePattern);
// ^^^ Problem seems here
Okey let's say you successfully parse this ASPxLabelCurrentTime.Text with usDtfi culture (which is en-US), but with this .ToString(string) method, you are not using currentDtfi settings actually, you are using CurrentCulture settings when you generate formatted string representation of your DateTime.
From DateTime.ToString(String) doc;
Converts the value of the current DateTime object to its equivalent
string representation using the specified format and the formatting
conventions of the current culture.
Since we don't know what GetCultureSelected method returns exactly, it may or may not be the same culture with currentDtfi.
I strongly suspect, you can solve this problem to using that culture as a second parameter in ToString method as;
ASPxLabelCurrentTime.Text = Convert.ToDateTime(ASPxLabelCurrentTime.Text, usDtfi)
.ToString(currentDtfi.ShortDatePattern, currentDtfi);
IF this (70) is really part of on your string, you need to ParseExact or TryParseExact methods to supply exact format of it.
string s = "11/2/2015 4:14 PM (70)";
DateTime dt;
if(DateTime.TryParseExact(s, "MM/d/yyyy h:mm tt '(70)'", CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
ASPxLabelCurrentTime.Text = dt.ToString(currentDtfi.ShortDatePattern, currentDtfi);
}

Format String to specific datetime [duplicate]

This question already has answers here:
CONVERT MM/DD/YYYY HH:MI:SS AM/PM to DD/MM/YYYY in C#
(3 answers)
Closed 8 years ago.
I want to convert the string "2015/07/05" to the format 08-MAR-2015.
The code below keeps getting detected as an invalid datetime format (i.e the else statement below)
C# Code
string format = "dd-MMM-yyyy";
string dateString = "2015/07/05";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,DateTimeStyles.None, out dateTime))
{
MessageBox.Show(Convert.ToString(dateTime));
}
else // Invalid datetime format
{
MessageBox.Show("UBD date is not a valid date format: " + dateTime.ToString());
}
String formatting is performed by the String.Format method, not Convert.ToString. The Convert methods try to convert one type to another using the current culture's default format where required.
Try the following
String.Format(CultureInfo.InvariantCulture,"dd-MMM-yyyy",someDate);
This will ensure that the English month names will be used.
In non-English cultures the following line will return the local month name
String.Format("dd-MMM-yyyy",someDate);

How to correctly parse a DateTime in this format: "2013-04-29T00:00:00" [duplicate]

This question already has answers here:
Parsing ISO 8601 string to DateTime in .NET? [duplicate]
(2 answers)
Closed 9 years ago.
I consume a web service which returns me some dates as string, and I use DateTime.Parse to get the correspondente DateTime objects. It is working, but I'm afraid my usage of DateTime.Parse may be vulnerable to bugs caused by different locale settings. The date returned is in the following format:
2014-04-24T00:00:00
The code I use to parse it:
DateTime d = DateTime.Parse(strValue);
Is there some way (such as passing a format provider, or using another method) in which I guarantee that my parsing routine will work regardless of the machine locale settings?
You are using the shortest form! Your format is ISO 8601-format (http://nl.wikipedia.org/wiki/ISO_8601). It is recognized with any culture!
So your way is the simplest way: DateTime result = DateTime.Parse("2008-06-15T21:15:07");
If you are not sure, use: DateTime result = DateTime.ParseExact("2008-06-15T21:15:07", "s", null);
Check out: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx#properties
If you want to parse a date independent of the user's locale, then use the invariant culture:
DateTime d = DateTime.Parse(strValue, CultureInfo.InvariantCulture);
Since you have an exact format, I'd use a non-ambiguous format string:
DateTime.ParseExact("2014-04-24T00:00:00", "yyyy\\-MM\\-dd\\THH\\:mm\\:ss", null)
// or to reduce the C#-escaped backslashes:
DateTime.ParseExact("2014-04-24T00:00:00", #"yyyy\-MM\-dd\THH\:mm\:ss", null)
The escaped hyphens and colons, as well as the escaped T, mean that those are constant values. So this line should work regardless of any other factors.
Yes, you could use the DateTime.ParseExact
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "2013-04-29T00:00:00";
format = "s";
result = DateTime.ParseExact(dateString, format, provider);
Where the "s" format string represents a sortable DateTime (MSDN on Format Strings)
string dateString;
DateTime dateValue;
// Parse a string.
dateString = "2014-04-24T00:00:00";
if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);

Categories

Resources