I'm converting date to Spanish using following code:
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
string s_date = dateValue.ToLongDateString();
Output is:
sábado, 04 de febrero de 2017
Now, I need to captilize DayName and MonthName. Please let me know how this can be acheived.
Expected Output:
Sábado, 04 de Febrero de 2017
TextInfo textInfo = new CultureInfo("es-ES",false).TextInfo;
string s_date = textInfo.ToTitleCase( dateValue.ToLongDateString()).Replace(" De ", " de ");
Related
I have to run through thousands of Word document and create XML files out of them. Everything works fine except the Date fields because I'm working in two languages.
Here are a few examples
DATE: NOVEMBER 24, 2016 TIME: 15:31
DATE: 28 NOVEMBRE 2016 HEURE: 10H31
I cleanup up the string a bit using the below but I still get the infamous 'String was not recognized as a valid DateTime.'
IFormatProvider culture = null;
if (m.rdoEnglish.IsChecked == true)
{
culture = new System.Globalization.CultureInfo("en-CA", true);
}
else if (m.rdoFrench.IsChecked == true)
{
culture = new System.Globalization.CultureInfo("fr-CA", true);
}
string dt = "";
dt = m.txtPublished.Text;
if (dt.IndexOf("HEURE:") != -1)
{
dt = dt.Replace("HEURE:", "");
}
if (dt.IndexOf("H") != -1)
{
dt = dt.Replace("H", ":");
}
DateTime dt2;
dt2 = DateTime.ParseExact(dt, "MM/dd/yyyy HH:mm:ss tt", culture);
//Cleaned string looks like this " 28 NOVEMBRE 2016 10:31 "
return dt2;
Looks like your format string is incorrect, in light of the two examples you gave.
It should be something like "MMMM dd, yyyy hh:mm"
Read more about it at:
DateTime.ParseExact Method
The ParseExact, as well TryParseExact, has an overload that accepts an array of formats to use in parsing the string. This will allow you to use something like this
string test = dt.Replace("DATE: ", "")
.Replace("TIME: ", "")
.Replace("HEURE: ", "");
string[] formats = new string[]
{
"MMMM dd, yyyy HH:mm", "dd MMMM yyyy HH\'H\'mm"
};
DateTime dt2 = DateTime.ParseExact(test, formats, culture, DateTimeStyles.None);
Notice that I don't try to replace the single char H inside the french version of your string because I don't know if the same char appears somewhere in your months.
I want to convert a datetime to string.
But result now is returned as 04 August, 0016 which is not what I need.
I want result to be 04 August, 2016.
C# code:
DataTable dtGroupCurr = new DataTable();
dtGroupCurr = sourceGroupCurr.Tables[0];
var groupedCurr = (from dt2 in dtGroupCurr.AsEnumerable()
select new
{
S_DATE = dt2.Field<DateTime>("S_DATE"),
BANK_CODE = dt2.Field<string>("BANK_CODE"),
BANK_NAME = dt2.Field<string>("BANK_NAME")
}).Distinct().OrderBy(x => x.S_DATE);
foreach (var s in groupedCurr)
{
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
}
Thanks in advance ;)
Try:
string sDate = s.S_DATE.ToString("dd MMMM, yyyy", new CultureInfo("en-US", true));
Or
string rDate = s.S_DATE.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); // To avoid override
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
The "/" custom format specifier represents the date separator, which
is used to differentiate years, months, and days. The appropriate
localized date separator is retrieved from the
DateTimeFormatInfo.DateSeparator property of the current or specified
culture.
MSDN
Use the DateTime.ParseExact method and specify the format like below:
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.ParseExact(rDate, "yyyy/MM/dd", culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
Use Date or DateTime.ToShortDateString();
Or
Date.ToString("dd-MM-yyyy");
I am unable to convert the string values that has been extracted from the ddl to a DateTime datatype.
The Error Message
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code. Additional information: String was
not recognized as a valid DateTime.
I only require the date to be updated in the SQL database.
This is the an image of the DataDictionary and the Attribute I require would be the birthdate
These are my current codes that get and convert the date time.
string birth = ddlDay.SelectedItem.Value + "-" + ddlMonth.SelectedItem.Value + "-" + ddlYear.SelectedItem.Value;
DateTime birthDate = DateTime.ParseExact(birth, "dd-MMMM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
objCustomer.birthDate = birthDate;
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
Instead of ParseExact you could use TryParse to be safe. ie:
var ddlDaySelectedItemValue = "29";
var ddlMonthSelectedItemValue = "Feb"; // February, 2, 02
var ddlYearSelectedItemValue = "2016";
DateTime birthDate;
string birth = ddlYearSelectedItemValue + " " + ddlMonthSelectedItemValue + " " + ddlDaySelectedItemValue;
if (DateTime.TryParse(birth, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
{
objCustomer.birthDate = birthDate;
}
Change your code to:
DateTime.ParseExact(birth, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
How can I convert a string representing 12-hour time into a time-only, 24hr format? Here's my code so far.
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
s = String.Format("{0:HH:mm:ss}", ar[0]);
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
DateTime dateTime = DateTime.Parse(ar[0]);
dateTime.ToString("HH:mm");
string s = "7:00 PM";
DateTime dt = Convert.ToDateTime(s);
Console.WriteLine(dt.ToString("HH:mm"));
Try this way
string[] ar;
string s = "7:00 AM - 9:00 AM";
ar = s.Split('-');
s = Convert.ToDatetime(ar[0]).ToString("HH:mm");
Can i convert the string below to DateTime
Friday, 27th September 2013
This is what i want to achieve:
String tmpDate="Friday, 27th September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
Doing above i get error:
The string was not recognized as a valid DateTime. There is an unknown
word starting at index 10.
Well, I'm not sure there is exactly solution with -th, -st, -nd, but you can use this like;
string tmpDate = "Friday, 27 September 2013";
DateTime dt = DateTime.ParseExact(tmpDate,
"dddd, dd MMMM yyyy",
CultureInfo.InvariantCulture);
Here a DEMO.
I almost suggest you remove -th, -st and -nd part of your string but these are break the rules :)
August
Monday
Thursday
Sunday
Also check Habib's answer which seems nice.
You can maintain the ordinals to remove in an array like this (which might make it easier to add/remove ordinals from other languages). That way you don't have to manually remove the ordinal from each string input. Using TryParseExact avoids an exception being thrown if the DateTime could not be parsed from the string.
String tmpDate = "Friday, 27th September 2013";
string[] split = tmpDate.Split();
string[] ordinals = new string[] { "th", "nd", "st" };
foreach (string ord in ordinals)
split[1] = split[1].Replace(ord, "");
tmpDate = String.Join(" ", split);
DateTime dt;
if(DateTime.TryParseExact(tmpDate, "dddd, dd MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("Parsed");
}
else
{
Console.WriteLine("Could not parse");
}
Your answer is in the exception you are getting. Obviously, "th" is not needed here. Just remove it and you are good to go.
This is working perfectly fine for me
String tmpDate = "Friday, 27 September 2013";
closingDate = Convert.ToDateTime(tmpDate).ToString("yyyy-MM-dd");
you will have to remove the th, nd,rd and st manually, as there isn't any format that takes these into account. After that you can use try parse exact like below
String tmpDate = "Friday, 27th September 2013";
tmpDate = tmpDate.Replace("nd", "")
.Replace("th", "")
.Replace("rd", "")
.Replace("st", "");
string[] formats = { "dddd, dd MMMM yyyy" };
DateTime dt;
if (DateTime.TryParseExact(tmpDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dt))
{
//parsing is successful
}
Assuming the format of the date string you provide does not change, the -st, -nd and -th can easily be removed (as already suggested).
Also be sure to provide a valid (existing) date, or a System.FormatException will be thrown.
string tmpDate = "Friday, 27th September 2013";
string[] splitDate = tmpDate.Split(new Char[] {' '});
splitDate[1] = splitDate[1].Substring(0, splitDate[1].Length-2);
string tmpDatewithoutStNdTh = String.Join(" ", splitDate);
try{
string closingDate = Convert.ToDateTime(tmpDatewithoutStNdTh).ToString("yyyy-MM-dd");
Console.WriteLine(closingDate.ToString());
}
catch(System.FormatException)
{
Console.WriteLine("The provided date does not exist.");
}
See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}