DateTime Format check - c#

Quick Question
Value passed in ActivationDate or ExpirationDate string, must be in either of the two formats stated below:Format 1:YYYY-MM-DD & Format 2: YYYY-MM-DD HH:MM
If the date values are not in either of the above format, then it should report back appropriate error message.
Any clue? Thanks in advance

You can use DateTime.TryParseExact, using a string[] with the valid formats:
string[] formats = new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm" };
string s = "2017-12-01 12:23";
DateTime date;
bool converted = DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
With this code, you get in convertedif the input date was in a valid format, and in date the parsed DateTime

You can use ParseExact() with try-catch:
string date = "2017-02-01";
DateTime dt = default(DateTime);
try
{
dt = DateTime.ParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-dd hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException ex)
{
//error
}
OR
Use TryParseExact():
string date = "2017-02-01";
DateTime dt;
if (DateTime.TryParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-DD hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//do something and use "dt" variable
}
else
{
//error
}

Related

c#.net String To Date Time

suppose i have a string date = "30-10-2018 15:00:00"
how can i save it a datetime variable depending on pc region and time settings
This is what I got so far:
DateTime evtd;
try
{
switch (cmbDateType.SelectedIndex)
{
case 1:
//India
string dateString = dr.Cells[10].Value.ToString(),
fmt = "dd-MM-yyyy HH:mm:ss";// "g";
CultureInfo provider = CultureInfo.InvariantCulture;
//provider=new CultureInfo("en-IN");
//CultureInfo In = new CultureInfo("en-IN");
//"dd-MM-yyyy HH:mm:ss"
//string fmt = In.DateTimeFormat.FullDateTimePattern;
evtd = DateTime.ParseExact(dateString, fmt, provider);
dtBillsEBN.Rows[i]["evtd"] = evtd; //Valid Till Date
break;
case 2:
//usa:"M/d/yyyy h:mm:ss tt"
evtd = DateTime.ParseExact(dr.Cells[10].Value.ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
dtBillsEBN.Rows[i]["evtd"] = evtd; //Valid Till Date
break;
default:
dtBillsEBN.Rows[i]["evtd"] = DBNull.Value;
break;
}
}
catch (Exception ex)
{
string msg = "Try Formating Valid Till Datein correct Format \nor\nchoose skip valid date update ";
MessageBox.Show(ex.ToString());
}
I have had issues string dates and converting them. Explicitly stating the date formats to check against helped.
something like this.
public static string[] DateTimeFormats => new string[]
{
"dd-MM-yyyy",
"MM/dd/yyyy",
"MM-dd-yyyy",
"d-MM-yyyy",
"d-M-yyyy",
"dd-M-yyyy",
"dd/MM/yyyy",
"yyyy/MM/dd HH:mm",
"dd-MM-yyyy hh:mm",
"dd-MM-yyyy HH:mm",
"MMMM yyyy"
};
and then when it comes to the converting of the string date.
internal static DateTime ChangeDateFormat(string dateAdded)
{
return ParseDateTime(DateTime.Now.ToString("dd-MM-yyyy hh:mm"), DateTimeFormats);
}
public static DateTime ParseDateTime(string dateTimeString, string[] formats)
{
try
{
DateTime dateStamp = DateTime.ParseExact(dateTimeString,
formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
return dateStamp;
}
catch (Exception exe)
{
var message = $"dateTimeString: '{dateTimeString}', '{string.Join(",", formats)}'.";
Utility.log(message);
throw;
}
}
Use DateTime.Parse()
DateTime.Parse("30-10-2018 15:00:00")

Converting string to date 12/29/2014 00:00:00.000

I am not able to convert a string of following format "12/29/2014 00:00:00.000"
to a datetime value....I tried using following code.
Can someone help me please.
var value = "12/29/2014 00:00:00.000";
DateTime validDate = new DateTime();
DateTime.TryParseExact(value, "yyyy-MM-dd HH:mm:ss.SSS", null,System.Globalization.DateTimeStyles.None,out validDate);
DateTime.TryParseExact(value, "MM/dd/yyyy HH:mm:ss.SSS", null, System.Globalization.DateTimeStyles.None, out validDate);
DateTime.TryParseExact(value, "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out validDate);
Console.WriteLine(validDate);
try this one
DateTime myDate = DateTime.ParseExact("12/29/2014 00:00:00.000", "MM/dd/yyyy HH:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture)
Try this one
using System;
public class Program
{
public static void Main()
{
var date = "12/29/2014 00:00:00.000";
IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
DateTime checkindate = Convert.ToDateTime(date, culture);
Console.WriteLine(checkindate);
}
}
use CultureInfo
Thanks
Change: DateTime.TryParseExact(value, "MM/dd/yyyy HH:mm:ss.SSS",
To: DateTime.TryParseExact(value, "MM/dd/yyyy HH:mm:ss.fff",
According to: https://msdn.microsoft.com/de-de/library/system.datetime.millisecond(v=vs.110).aspx

Fixing Dates in C#

I am trying to create a textbox that will translate 1225 to 12/25/13. After having done a lot of research, I think "DateTime.TryParseExact" is what I need to use, but I can't get it to work. Here is my code:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
string[] DateTimeFormats = new string[]{
"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss"};
if (DateTime.TryParseExact(TheTextBox.Text, DateTimeFormats, provider, DateTimeStyles.None, out dateValue))
{
TheTextBox.Text = dateValue.ToString("d MMMM yyyy");
}
Any ideas how to fix this?
If it is possible to predict all possible formats, then you can try something like this
static void Main(string[] args)
{
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "0501";
var dateFormats = new String[] {"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss", "MMdd"};
bool matchFound = false;
foreach (var dateFormat in dateFormats)
{
if (DateTime.TryParseExact(dateString, dateFormat, enUS, DateTimeStyles.None, out dateValue))
{
matchFound = true;
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue.ToString("dd MM yyyy"), dateValue.Kind);
}
}
if (!matchFound)
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
Console.ReadKey();
}
For the example you provided consider the following change to your code...
string[] DateTimeFormats = new string[]{"MMdd"};
You can use DateTime.ParseExact to translate your string into a DateTime:
The text of the textBox1 is 1225:
DateTime date = DateTime.ParseExact(textBox1.Text,"MMdd",CultureInfo.InvariantCulture);
string yourDate = date.ToString("MM/dd/yy"));
//yourDate is 12/25/13
Note: This will always return the date with the current year (here: 2013).

asp.net | Time Zone | Format | CultureInfo

I need to convert datetime to en-us culture format ...
but our users are in different locality; some people follow
DD.MM.YYYY hh:mm:ss tt,
I'm getting an error
"String was not recognized as a valid
DateTime"
while converting the
time zone to MM/DD/YYYY hh:mm:ss tt
(en-us).
System.Globalization.CultureInfo oCulture = new System.Globalization.CultureInfo("en-US", false);
public string CultureStringFormat(string Date)
{
DateTime _Datetime = DateTime.Now;
try
{
_Datetime = DateTime.Parse(Date);
return _Datetime.ToString("G", oCulture);
}
catch (Exception ex)
{
try
{
_Datetime = DateTime.Parse(Date, oCulture);
return _Datetime.ToString("G", oCulture);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
return "";
}
public DateTime CultureDateFormat(string Date)
{
try
{
return DateTime.Parse(Date, oCulture, DateTimeStyles.NoCurrentDateDefault);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return DateTime.Now;
}
Thread.CurrentThread.CurrentCulture = oCulture;
string sDate = CultureStringFormat("28.12.2011 10:15:07"); // i'm getting an Error
DateTime dtDate = CultureDateFormat("28.12.2011 10:15:07"); // Error
string sDate1 = CultureStringFormat("12.27.2011 10:15:07"); // i'm getting success 12/27/2011 10:15:07 AM
DateTime dtDate1 = CultureDateFormat("12.27.2011 10:15:07"); //success 12/27/2011 10:15:07 AM
Thread.CurrentThread.CurrentCulture = oCulture; //Without this line ...
string sDate = CultureStringFormat("28.12.2011 10:15:07"); // success 12/28/2011 10:15:07 AM
DateTime dtDate = CultureDateFormat("28.12.2011 10:15:07"); // Error
string sDate1 = CultureStringFormat("12.27.2011 10:15:07");// success 12/27/2011 10:15:07 AM
DateTime dtDate1 = CultureDateFormat("12.27.2011 10:15:07");// Wrong 27.12.2011 10:15:07
You need to use DateTime.TryParseExact. The snippet below should get you started in the right direction:
string myDate = "17.11.2011 08:00:00 AM";
DateTime parsedDate;
DateTime.TryParseExact(myDate,
"dd.MM.yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out parsedDate);
public DateTime? GetDate(string dateString)
{
var formats = new string[]
{
"dd.MM.yyyy hh:mm:ss",
"MM/dd/yyyy hh:mm:ss",
"dd.MM.yyyy HH:mm:ss",
"MM/dd/yyyy HH:mm:ss",
"dd.MM.yyyy hh:mm:ss tt",
"MM/dd/yyyy hh:mm:ss tt"
};
DateTime date;
if ( DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out date))
{
return date;
}
return null;
}

Format string as date

I have a string 20100524 (2010 05 24) and I would like to parse it as an actual date format.
This will do it for you in a safe manner:
DateTime dateTime;
if (DateTime.TryParseExact("20100524", "yyyyMMdd", null, DateTimeStyles.None, out dateTime))
{
// use dateTime here
}
else
{
// the string could not be parsed as a DateTime
}
DateTime.Parse and Datetime.ParseExact are your friends.
DateTime.ParseExact("20100524", "yyyyMMdd", Thread.CurrentThread.CurrentCulture);
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "20100524";
string format = "yyyyMMdd";
result = DateTime.ParseExact(dateString, format, provider);

Categories