I have a string 11,111 its coming from database now i want to check that if this string is a datetime then parse it into datetime but if its not then leave it as it is but DateTime.Parse is parsing it into date 01/11/0111 12:00 AM which is
not correct . Here is my code
DateTime newDateTimeValue = default(DateTime);
DateTime.TryParse(each.NewValue, out newDateTimeValue);
if (newDateTimeValue != default(DateTime))
each.NewValue = Utility.FormatDate(DateTime.Parse(each.NewValue), dateFormat, culture);
And here is FormatDate function From Utility Class
public static string FormatDate(DateTime? dt, string dateFormat, string language)
{
if (dt.HasValue)
{
string offset = string.Format("{0:0.00}", Convert.ToDouble(HttpContext.Current.Session["Offset"]));
string offsetSign = offset.Contains("-") ? "-" : string.Empty;
if (language == "en-US")
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf('.')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf('.') + 1, offset.Length - offset.IndexOf('.') - 1)));
else
{
try
{
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf(',')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf(',') + 1, offset.Length - offset.IndexOf(',') - 1)));
}
catch
{
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf('.')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf('.') + 1, offset.Length - offset.IndexOf('.') - 1)));
}
}
dateFormat = dateFormat + " hh:mm tt";
if (dateFormat == "MMM dd, yyyy hh:mm tt" || dateFormat == "dd MMM yyyy hh:mm tt")
return dt.Value.ToString(dateFormat, new CultureInfo(language));
else
return dt.Value.ToString(dateFormat, new CultureInfo("en-US"));
}
else
return string.Empty;
}
May help others
public void GetDate(string dateString)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "d";
try
{
if(DateTime.TryParseExact(dateString,provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format", dateString);
}
}
catch(FormatException)
{
Console.WriteLine("{0} is not in the correct format", dateString);
}
}
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 wrote code that could read the date in format dd/mm/yyyy hh:mm AM/PM, but now I need it to read date in the format if mm-dd-yyyy hh:mm Am/PM.
Can someone please guide me in right direction?
My code:
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
foreach (FileInfo fi in fiArray)
{
try
{
StreamReader reader = fi.OpenText();
string date;
string logContent = reader.ReadLine();
string patternDate = "(?<logDate>(\\d){2}-(\\d{2})-(\\d{4})\\s(\\d{2}):(\\d{2})\\s?(?i)(am|pm))";
Regex reg = new Regex(patternDate);
date = reg.Match(logContent).Value.ToString();
// for dt2, the error happens here
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
// DateTime dt2 = DateTime.ParseExact(date, format, provider);
while ((line = reader.ReadLine()) != null)
{
Regex reg1 = new Regex("^(ARCH(?!9{2}))");
bool flag = reg1.IsMatch(line);
if (flag == true)
{
string dt = DateTime.Now.ToString("yyyymmddHHMMss");
string[] values = line.Split(',').Select(sValue => sValue.Trim()).ToArray();
// string uniqueGuid = SequentialGuidGenerator.NewGuid().ToString();
string uniqueGuid = Utility.generateID();
uniqueGuid = uniqueGuid.Replace("-", "").Substring(0,18);
string RPT_ID = values[0].ToString();
RPT_ID = RPT_ID.Remove(0, 4);
table.Rows.Add(uniqueGuid, RPT_ID, values[1].ToString(), dt2);
}
else
{ }
}
reader.Close();
}
catch (MyException e)
{
throw e.MyExceptiona(e, fi);
}
}
Utility.InsertData(table);
This code is reading 01-02-2016 12:40 AM but I need it to read 01-15-2016 12:40 AM
Try like this
DateTime parsedDate ;
string YourDate = "01-15-2016 12:40 AM";
string pattern = "MM-dd-yyyy hh:mm tt";
DateTime.TryParseExact(YourDate, pattern, null,
DateTimeStyles.None, out parsedDate);
how about :
DateTime mydt;
DateTime.TryParseExact("01-16-2016 12:40 AM", "MM-dd-yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out mydt)
For reference about custome datetime parsing : https://msdn.microsoft.com/fr-fr/library/8kb3ddd4(v=vs.110).aspx
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);
string strDateFrom;
string strDateTo;
CrystalDecisions.Shared.ParameterDiscreteValue DateValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
if ((strDateFrom != "") && (strDateTo != ""))
{
DateValue.Value = "(From: " + strDateFrom + " - " + strDateTo + ")";
}
else
{
DateValue.Value = "(ALL DATES)";
}
You can use DateTime.Parse
string date = "2020-02-02";
DateTime time = DateTime.Parse(date);
Console.WriteLine(time);
Or use:
DateTime oDate = DateTime.Parse(string s);
If you know the format used, you can try DateTime.ParseExact() or DateTime.TryParseExact():
String text = "30/12/2013";
DateTime result = DateTime.ParseExact(text, "d/M/yyyy", CultureInfo.InvariantCulture);
In order to avoid formatting issue, I prefer using DateTime.ParseExact or DateTime.TryParseExact.
basically the difference between those methods and DateTime.Parse is weather you know the date format of the string (and then you use DateTime.ParseExact) or not (and then use DateTime.Parse).
You can read more about ParseExact and TryParseExact
EDIT:
Example code from the links:
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
Say I have the following:
string fromTime = "8:00am";
string someDate = "06/01/2012";
I want to end up doing this:
DateTime dt = Convert.ToDateTime(someDate + someTime);
Basically I want to take a date and add the time to it with the result for the above to be
06/01/2012 8:00am
But have it stored in a datetime variable. Is this possible?
You could use the DateTime.TryParseExact method which allows you to specify a format when parsing:
class Program
{
static void Main()
{
string s = "06/01/2012 8:00am";
string format = "dd/MM/yyyy h:mmtt";
DateTime date;
if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
}
}
Try this:
DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);