DateTime date = new DateTime(1970, 1, 15);
string sdate = date.ToString(value_i_will_forget as string,
CultureInfo.InvariantCulture);
// some lines later
string format_string = MagicParse(sdate,
CultureInfo.InvariantCulture);
I have an arbitrary date that I write to a string with CulturInfo.InvariantCulture. The .Net format I use - "d", for example - is now forgotten.
I do know however that the string hasn't changed, its still valid and its still with invariant culture. Im looking for the MagicParse function to extract the format string used to write the formatted date.
Unless you have a sample of dates in which the day exceeds 12, then there is no feasible way that this would ever be safe.
DateTime.Parse(your_date_string, CultureInfo.InvariantInfo)
, also you can add specific DateTimeStyles in third parameter
Try this one
http://msdn.microsoft.com/en-US/library/system.globalization.datetimeformatinfo.shortdatepattern.aspx
Related
I'm trying to parse two separate fields, a date and a time, into one DateTime object as strings. The date has padding, the time doesn't, but they follow a consistent format, with date being something like 07302018 and time being 101230; an issue being, as well, that time could be something like 91230. What I've tried right now:
string timeformat1 = "MMddyyyy HHmmss";
string timeformat2 = "MMddyyyy Hmmss";
string date = "07302018"
string time = "63020"
if (time.Length == 6)
{
datetimeobject = DateTime.ParseExact($"{date} {time}", timeformat1, CultureInfo.InvariantCulture);
}
else
{
datetimeobject = DateTime.ParseExact($"{date} {time}", timeformat2, CultureInfo.InvariantCulture);
}
Doesn't seem to work, giving a "String was not recognized as a valid DateTime" exception.
Am I going to need to insert some slashes and punctuation into the strings in order to make them read correctly? I wanted to avoid this because I had heard there are performance concerns with disassembling and reassembling strings, but I may have to do so unless there is a more elegant solution.
Try this to avoid ifs
string timeformat = "MMddyyyy HHmmss";
string date = "07302018";
string time = "91230";
string joint = $"{date} {time.PadLeft(6,'0')}";
DateTime datetimeobject = DateTime.ParseExact(joint, timeformat, System.Globalization.CultureInfo.InvariantCulture);
The DateTime.ParseExact will fail with a single char for hour and the single H because it need a separation between hour and other values. From MSDN:
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMddHHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
I have changed my system date format to Faeroese.
I want to convert DateTime to String according to customCulture with G format (combination of date and Time)
check the below code.
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime dateTimeValue = (DateTime)value;
CultureInfo customCulture = MySettings.getCustomCulture();
//for getting custom culture in my app
//in custom culture i have changed shortDateFormat according to the user preference.
//value in shortDateFormat = dd/MM/yyyy
string result = string.Format(customCulture, "{0:G}", result);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
but i get the output with sepertators according to system DateTime not with users given format in customCulture,
i even dont find any method overloaded in string.Format() or DateTime.ToString() to do this.
If i pass CultureInfo.InvariantCulture then i cant get output in G format.
try this:
DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
Console.WriteLine(date1.ToString("G", DateTimeFormatInfo.InvariantInfo));
// Displays 04/10/2008 06:30:00
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("en-us")));
// Displays 4/10/2008 6:30:00 AM
Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("nl-BE")));
According to Standard Date and Time Format Strings "G" uses short date format (as you claim to specify). So most likely reason of using local culture separator is covered in The "/" Custom Format Specifier portion of ""Custom Date and Time Format Strings".
Since your "short date format" is "dd/MM/yyyy" than instead of "/" it will use corresponding separator from the culture info (which you are likely picking from default culture).
Escaping with \ is covered in the Using the escape character portion of the same "Custom Date and Time Format Strings" article.
So you want your shortDateFormat = #"dd\/MM\/yyyy" or properly specify DateTimeSeparator in corresponding part of your custom CultureInfo.
How can I convert the String 20120313 to a DateTime object that holds the value 13-Mar-2012?
I fetch it as
DataEffectiveDate = Convert.ToDateTime(reader["date_id"]);
But it fails here already (converting to 1/1/2001)
You need to use DateTime.ParseExact:
DateTime date = DateTime.ParseExact(text, "yyyyMMdd",
CultureInfo.InvariantCulture);
Then if you want it as "13-Mar-2012", you need:
string reformatted = date.ToString("dd-MMM-yyyy");
... optionally passing in whatever culture you want to use for the month names etc.
(Another alternative is to use my Noda Time, which allows you to parse this as just a local date, without any concerns about what time it will use, time zones etc.)
When you have a particular format in mind, ParseExact is helpful:
string s = "20120313";
var when = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
There's also an overload that accepts multiple candidate formats.
Try DateTime.ParseExact:
string date = DateTime.ParseExact(reader["date_id"], "yyyyMMdd", new CultureInfo("en"));
I have the following function
DateTime fromDateParam = DateTime.ParseExact(Convert.ToString(DateTime.MinValue),"dd.MM.yyyy HH:mm:ss",null);
It says input string not recognised as a valid date.
Any ideas how I can get any the min date recognised to parse exact?
Well you're converting the original time to a string using the default formatting, but then you're specifying custom formatting for the parsing.
If you specify a format string using DateTime.ToString(format) and keep the format consistent, it works fine:
string formatString = "dd.MM.yyyy HH:mm:ss";
string text = DateTime.MinValue.ToString(formatString);
Console.WriteLine(text);
DateTime fromDateParam = DateTime.ParseExact(text, formatString, null);
In other words (continuing Skeet's answer), Convert.ToString(DateTime.MinValue) is based on current/default CultureInfo, etc.
I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message