Incorrect DateTime format - c#

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

Related

Combine date and time from string and convert to datetime

I have 2 strings (date(13/04/2021),time("06:30")) and I want to combine them together to datetime format and I am getting the below error.
System.FormatException: 'String was not recognized as a valid DateTime.'
What I am doing wrong?
if I change the tempdate format to "yyyy-dd-MM" I get the error there
var type = form["GymType"];
var time = form["states_ddl"];
var date = form["date2"];
var username = form["username"];
var numberofpersons = 0;
if (type == "2")
{
//gym
numberofpersons = 9;
}
else
{
//cross
numberofpersons = 5;
}
Booking toadd = new Booking();
var currenduser = User.Identity.GetUserId();
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(tempdate + " " + time, "yyyy-dd-MM HH:mm", CultureInfo.InvariantCulture);
What you do is convert de string to a dateTime 'tempdate', and than on the next line you convert it back to a string.
What i would do is convert the date as you do and parse the time separate, than add them together.
var tempdate = DateTime.ParseExact(date , "dd/MM/yyyy", CultureInfo.InvariantCulture);
var timspan = TimeSpan.Parse(time);
DateTime d = tempdate.Add(timspan);
You can use Convert to do this
var date = Convert.ToDateTime("13/04/2021 06:30");
try this
string d = "13/04/2021";
string t = "10:30PM";
string dateAndTime = d.Trim() + ' ' + t.Trim();
DateTime dt = DateTime.ParseExact(dateAndTime, "MM/dd/yyyy hh:mmtt",
CultureInfo.InvariantCulture, DateTimeStyles.None);
dt = DateTime.Parse(dateAndTime, CultureInfo.InvariantCulture,
DateTimeStyles.None);

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.

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

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

DateTime.Parse not working correctly

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

take time and append to date to make datetime?

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

Categories

Resources