I have a method,
public static DateTime ToDate(this object value)
{
return DateTime.ParseExact(value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
}
When i run this code with this code,
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(DateTime.Now.ToDate().ToString());
}
And there is a error on program like this,
String was not recognized as a valid DateTime
How can i solve this problem?
Thanks.
The problem you're having is that your extension method tries to parse the string specifically in the dd.MM.yyyy format. And you're testing your extension method using the DateTime.Now which returns a DateTime in a format of a current culture on your machine (including hours, minutes, etc.), which may may not be in a dd.MM.yyyy format. You can test your extension method as follows: DateTime.Now.ToString("dd.MM.yyyy").ToDate()
However, If I understand correctly what you're trying to do it is better to change the extension method as follows.
public static DateTime ToDate(this string value, string format)
{
return DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
}
and use it as follows
private void button1_Click(object sender, EventArgs e)
{
// Testing the extension method.
MessageBox.Show(DateTime.Now.ToString("dd.MM.yyyy").ToDate("dd.MM.yyyy").ToString());
}
Or, if you specifically receive a DateTime in dd.MM.yyyy because of the localization it is better to set the culture of your application globally like so.
// Substitute appropriate culture.
Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");
That way you will not need your extension method since the DateTime will always be in the correct format.
your first function must be as follow :
public static DateTime ToDate(this object value)
{
string date = value.ToString("dd.MM.yyyy");
DateTime dt = Convert.ToDateTime(date);
return dt;
}
I suggest to use the TryParseExact
Then you choose the date format that you need
For example :
public static DateTime ToDate(this object value)
{
DateTime OutputDate ;
DateTime.TryParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
return OutputDate ?? DateTime.Now ;
}
In the example : the format is "dd.MM.yyyy" and the input date string is value. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.
Please, verify the format of the date and replace it in the example above if you need
Related
I am reading string inputs from an excel sheet and I want to check if the string is a valid date.
To do so, I have:
public static bool IsValidDate(string DateStr)
{
DateStr = DateStr.Trim();
DateTime tempDate = new DateTime().Date;
return DateTime.TryParse(DateStr, out tempDate);
}
The problem in here is that in case that string is 13/12/2021 it will return false(not valid) because set 13 as month and 12 as day.
What is the proper approach to manipulate string format and do a right check inside the same function?
Any help is welcome!
Try this:
public static bool IsValidDate(string DateStr)
{
DateStr = DateStr.Trim();
DateTime tempDate = new DateTime().Date;
return DateTime.TryParse(DateStr, new System.Globalization.CultureInfo("de-DE"), System.Globalization.DateTimeStyles.None, out tempDate);
}
You have to extend the method to take a CultureInfo/DateTimeFormatInfo that uses a format string which starts with the days instead of the month. You could use this:
public static bool IsValidDate(string dateStr, out DateTime theParsedDateTime, IFormatProvider fp = null)
{
if (fp == null)
fp = DateTimeFormatInfo.InvariantInfo;
return DateTime.TryParse(dateStr.Trim(), fp, DateTimeStyles.None, out theParsedDateTime);
}
Now you can call this method in this way, i have used german CultureInfo because that is a working example. Note that InvariantInfo doesn't work because it starts with months:
bool valid = IsValidDate("13/12/2021", out DateTime parsedDate, new CultureInfo("de-DE"));
You have to create a CultureInfo with CultureInfo.CreateSpecificCulture.
And then parse the string using the specific culture.
Just see the example under.
This works for me.
public static bool IsValidDate(string DateStr)
{
return DateTime.ParseExact(DateStr, "dd/MM/yyyy", null);
}
I am trying to convert a string, 20151107 to the date format of 2015-11-07.
Here's my code :
public static DateTime CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt;
}
However this returns something like this 11/07/2015 12:00:00 AM.
Any idea?
Your date returns like that because you are returning the entire DateTime object and since you are not providing a time it is default to 00:00:00.00.
If you want to return the Date in a particular format, you can use the Standard Format Strings or a Custom Format String.
In your case, you want 2015-11-07 which is a custom format of yyyy-MM-dd and can be used like so:
public static string CustomDateFormat(string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MM-dd");
}
public static String CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MMM-dd");
}
I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.
I have a function that checks for null values then converts dates if they are not null
the below function just had "08/09/13" sent to it (English format) and i got "String was not recognized as a valid DateTime."
anyone help me as to why? do i need to tell the something somewhere is uses English format?
Thanks
public static DateTime DateTimeCheck(object objDateTime)
{
if (objDateTime == null || objDateTime == "")
return default(DateTime);
return Convert.ToDateTime(objDateTime);
}
I don't understand why you passed an object as a parameter instead of string first of all.
Try this instead;
public static DateTime DateTimeCheck(object objDateTime)
{
...
return DateTime.ParseExact(objDateTime.ToString(),"dd/MM/yy",CultureInfo.InvariantCulture);
}
Of course, this throws exception if your object is not formatted same as with "dd/MM/yy".
Take a look at;
Custom Date and Time Format Strings
You can use the overloaded method that accepts the culture information:
Convert.ToDateTime(o, new CultureInfo("en-Gb"));
To get or set the current culture you can use:
System.Threading.Thread.CurrentThread.CurrentCulture
You might be in a different culture with a different default date format. However you can use ParseExact to parse in the expected format. For example:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact("25/12/82","dd/MM/yy",provider);
I know this not what you are looking for but that's how to be sure that some object has date time value in it something like that :
public static DateTime DateTimeCheck(object objDateTime)
{
DateTime dateTime ;
if (objDateTime != null)
{
if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
{
return Convert.ToDateTime(objDateTime);
}
}
return default(DateTime);
}
Try this:
DateTime.ParseExact((string)objDateTime,"dd/MM/yyyy",CultureInfo.InvariantCulture);
I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");