C# ASP.NET: can't convert datetime to string - c#

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");

Related

Convert a string Date and Time to a DateTime

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.

Convert string dd/mm/yy to datetime

I need to convert a string format dd/mm/yy to a datetime.
I tried with:
DateTime d;
if (DateTime.TryParseExact(dateStr.Trim(), "dd/MM/yyyy", new CultureInfo("es-es"), DateTimeStyles.AssumeLocal, out d))
return d;
Your code seems ok, but also you can convert a string into datetime like below
DateTime d = DateTime.ParseExact("11/02/2016", "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d;
if you have string as dd/MM/yy format and need to convert it as dd/MM/yyyy fomat datetime then you can do like this
DateTime temp = DateTime.ParseExact("11/02/16", "dd/MM/yy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(temp.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d
string dateBirth = ddlDay.SelectedItem.ToString() + "/" + ddlMonth.SelectedItem.ToString() + "/" + ddlYear.SelectedItem.ToString();
DateTime dt = DateTime.ParseExact(dateBirth, "dd/MM/yyyy", null);

Giving Error String was not recognized as a valid DateTime

Well I've tried following:
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime DateTo;
string DateToStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
DateTo = DateTime.ParseExact(DateToStr, "yyyy-MM-dd HH:mm:ss", culture);
Also tried following:
DateTime DateTo;
string DateToStr = DateTime.Now.ToString("yyyy-MM-dd");
DateTo = DateTime.ParseExact(DateToStr, "yyyy-MM-dd", culture);
And following also:
DateTime DateTo;
string DateToStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
DateTo = DateTime.ParseExact(DateToStr, "yyyy-M-dd HH:mm:ss", culture);
Each time it is giving me the same error:
String was not recognized as a valid DateTime
Whats going wrong here?
Thanks in advance.
Try calling it with additional parameter
DateTo = DateTime.ParseExact(DateToStr, "yyyy-MM-dd HH:mm:ss", culture, DateTimeStyles.AllowWhiteSpaces);

How to convert string to a DateTime in C#?

is it possible to convert a string (date stored as varchar in database) to datetime in c#?
eg. i'm having a table which stores dates as varchar and it stores values as example
01/21/14 11:42:36 PM
i want to get the result in the format yyyy-mm-dd
i tried,
CultureInfo enUS = new CultureInfo("en-US");
DateTime d;
DateTime.TryParseExact("01/21/14 11:42:36 PM", "yyyy-mm-dd", enUS, DateTimeStyles.None, out d);
also tried below steps:
CultureInfo enUS = new CultureInfo("en-US");
DateTime d = Convert.ToDateTime("01/21/14 11:42:36 PM");
string dt = Convert.ToString(d);
DateTime.TryParseExact(dt, "MM/dd/yy hh:mm:ss tt", enUS, DateTimeStyles.None, out d);
var output = d.ToString("yyyy-mm-dd");
getting value 1/1/0001 12:00.. in dt.
what could be the reason? also in which format do i need to pass the date (dt in above case) to DateTime.TryParseExact(..)
The second parameter of your call should be the format you're passing. After the datetime is created you can specify the output format:
CultureInfo enUS = new CultureInfo("en-US");
DateTime d;
DateTime.TryParseExact("01/21/14 11:42:36 PM", "MM/dd/yy hh:mm:ss tt", enUS, DateTimeStyles.None, out d);
var output = d.ToString("yyyy-MM-dd");
String date = "01/21/14 11:42:36 PM";
DateTime dt = Convert.ToDateTime(date);
var output = dt.ToString("yyyy-MM-dd");

Getting error "String was not recognized as a valid DateTime."

I am getting error String was not recognized as a valid DateTime while converting string to datetime format. I am trying to convert "25-11-2013 06:25:33 PM" to date format. Do any one can help me to solve this issue.
protected void text_changed(object sender, EventArgs e)
{
if (frm.Text == "")
{
Label1.Visible = true;
Label1.Text = "You can leave from textbox blank";
return;
}
string dt = TextBox1.Text;
string amt = dt.ToString();
string ams = amt.ToString() + " " + frm.Text;
DateTime dts = DateTime.ParseExact(ams, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
string ams1 = amt.ToString() + "" + TextBox2.Text;
DateTime dts1 = DateTime.ParseExact(ams1, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
TimeSpan dur = DateTime.Parse(dts1.ToString()).Subtract(DateTime.Parse(dts.ToString()));
double res = 0.0;
res = dur.TotalHours * 20;
TextBox3.Text = res.ToString();
}
If what the user enters is "25-11-2013 06:25:33 PM" then your format string has to be:
string dateFormat = "dd-MM-yyyy hh:mm:ss tt";
The format string you have in your code "MM/dd/yyyy hh:mm:ss tt" requires the user to enter the date as "11/25/2013 06:25:33 PM". All the custom DateTime format string options are described here: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Use a calendar control
You are going to have issues with parsing the dates if you allow users to just enter a free form string. Your best option is to add a calendar control or some other way of structuring the user input so that you don't have to parse a free-form string.
Use the generic converter
Using Convert.ToDateTime will save you a bunch of hassle in setting up the expected formats as it tries it's best to find a date format that will fit. On the other hand you may not get what you expected if the date the user enters can be parsed in multiple ways...
string dts = "09/10/11 06:25";
DateTime dt = System.Convert.ToDateTime(dts);
On my Swedish system it gets converted to 2009-10-11, yy/mm/dd but using a US context the expected date is 2011-09-10, mm/dd/yy.
Use CultureInfo if you can
If you can get the user to indicate or select their culture then parsing date/times from free-form will be much easier - since the user is more likely to enter a culturally correct string.
//this is parsing the datetime using Swedish format
string theCulture = "sv-SE";
string localDts = "2013-11-25 06:25";
DateTime localDt = DateTime.Parse(localDts, System.Globalization.CultureInfo.CreateSpecificCulture(theCulture));
Use an array of format strings
If that isn't possible you should think about the different ways that a user may enter dates and times in your system and add them to an array of supported strings. You may need to add a load of different strings since each format string parses one exact format and the user may enter months,days,hours etc as single digits or omit the seconds part. Here is an example which parses a bunch of different formats, this is in no way complete coverage of all the alternatives...
//A few different strings to test
string dts1 = "25-11-2013 6:25:33";
string dts2 = "11/25/2013 6:25:33";
string dts3 = "25-11-2013 06:25:33";
string dts4 = "11/25/2013 06:25:33";
string dts5 = "25-11-2013 6:25:33 PM";
string dts6 = "11/25/2013 6:25:33 PM";
string dts7 = "25-11-2013 06:25:33 PM";
string dts8 = "11/25/2013 06:25:33 PM";
string dts9 = "25-11-2013 6:5:33 PM";
string dts10 = "11/25/2013 6:5:33 PM";
//The supported datetime formats as an array
string[] dateFormats = {
"dd-MM-yyyy hh:mm:ss tt",
"dd-MM-yyyy h:mm:ss tt",
"dd-MM-yyyy h:m:ss tt",
"dd-MM-yyyy HH:mm:ss",
"dd-MM-yyyy H:mm:ss",
"dd-MM-yyyy H:m:ss",
"MM/dd/yyyy hh:mm:ss tt",
"MM/dd/yyyy h:mm:ss tt",
"MM/dd/yyyy h:m:ss tt",
"MM/dd/yyyy HH:mm:ss",
"MM/dd/yyyy H:mm:ss",
"MM/dd/yyyy H:m:ss"
};
//Parse all the sample strings
DateTime dt1 = DateTime.ParseExact(dts1, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt2 = DateTime.ParseExact(dts2, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt3 = DateTime.ParseExact(dts3, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt4 = DateTime.ParseExact(dts4, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt5 = DateTime.ParseExact(dts5, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt6 = DateTime.ParseExact(dts6, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt7 = DateTime.ParseExact(dts7, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt8 = DateTime.ParseExact(dts8, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt9 = DateTime.ParseExact(dts9, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
DateTime dt10 = DateTime.ParseExact(dts10, dateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

Categories

Resources