I want to convert a string '30/12/2012' to '2012/12/30'. My application is set to "en-CA" however the database accepts yyyy/MM/dd as default.
How can I do this without depending on the current culture info set
at server?
As all the comments have said, but none of the answers have said so far: don't pass this to the database as a string.
Parse any text you receive as early as possible, then use DateTime to represent it everywhere else, including how you send it to the database, via parameterized SQL1. This goes for values of all kinds: convert it into the "natural" type for the data as soon as possible, and keep it in that natural representation for as long as possible. A date isn't a string, and you should only convert it to a string if you really, really need to - ideally just before displaying it to a user.
The parsing can be done with DateTime.ParseExact or DateTime.TryParseExact depending on whether this is "suspicious" data (e.g. from a user) or data which should really be correct and for which an exception is the most appropriate reaction to unparseable values. I suggest you pass in CultureInfo.InvariantCulture with your custom format string. For example:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
(If you do a lot of date/time work, you may also want to consider using my Noda Time project which allows you to express the value in a richer way - in this case you'd probably use LocalDate.)
1 If you're not already using parameterized SQL, but are instead baking values directly into the SQL, you have bigger problems than date/time conversions.
You can specify CultureInfo in Format and most ToString functions.
I.e. DateTime.ToString(CultureInfo) and DateTime.Parse(string, CultureInfo) will let you pars string in one culture (i.e. current or new CultureInfo("en-CA")) and format with another like new CultureInfo("en-us").
Note: you may consider running all DB access under some other culture (i.e. en-US) by setting Thread.CurrentCulture as sometimes number fomats are also impacted (if numbers are storead as string).
If its going to always be in the same format. Then split it on the / character
string[] tempsplit = datestring.Split('/');
and then put it back together
string joinstring = "/";
string newdate = tempsplit[2] + joinstring + tempsplit[1] + joinstring + tempsplit[0];
simple.
First convert your string to DateTime format using
DateTime dt = Convert.ToDateTime("your string value");
Then save it in string using:
string st=dt.ToString("yyyy/MM/dd");
This will convert your date format to any desired format you want without depending on culture
Without going into the issue what format the database accepts or not, you can do the conversion like this:
Convert the String to Datetime like explained here
Change the format and convert it to string again like this
This seems to work.
var x = new string[] { "2012/06/12", "20/06/2012", "111/111/1111" };
foreach (var ds in x)
{
DateTime d = default(DateTime);
try
{
d = DateTime.Parse(ds, CultureInfo.GetCultureInfo("en-CA"));
}
catch (Exception ex)
{
try
{
d = DateTime.ParseExact(ds, "yyyy/MM/dd", CultureInfo.InvariantCulture);
}
catch
{
}
}
if (d == default(DateTime))
Console.WriteLine("error");
else
Console.WriteLine(d.ToString());
}
Related
I have a string like this:
30/04/2018 o/p=300418
01/03/2017 o/p=010317
10/11/2018 o/p=101118
12/11/2123 o/p=121123
1/1/2018 o/p =010118
code tried but can't get the last one 1/1/2018
string a = "31/04/2018";
string b = a.Replace("/","");
b = b.Remove(4, 2);
You should parse to a DateTime and then use the ToString to go back to a string. The following works with your given input.
var dateStrings = new []{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};
foreach(var ds in dateStrings)
{
Console.WriteLine(DateTime.ParseExact(ds, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("ddMMyy"));
}
The only change I made is to the first date as that is not a valid date within that month (April has 30 days, not 31). If that is going to be a problem then you should change it to TryParse instead, currently I assumed your example was faulty and not your actual data.
Your structure varies, all of the examples above use two digit month and day, while the bottom only uses a single digit month and day. Your current code basically will replace the slash with an empty string, but when you remove index four to two your output would deviate.
The simplest approach would be:
var date = DateTime.Parse("...");
var filter = $"o/p = {date:MMddyyyy}";
Obviously you may have to validate and ensure accuracy of your date conversion, but I don't know how your applications works.
If you can reasonably expect that the passed in dates are actual dates (hint: there are only 30 days in April) you should make a function that parses the string into DateTimes, then uses string formats to get the output how you want:
public static string ToDateTimeFormat(string input)
{
DateTime output;
if(DateTime.TryParse(input, out output))
{
return output.ToString("MMddyy");
}
return input; //parse fails, return original input
}
My example will still take "bad" dates, but it will not throw an exception like some of the other answers given here (TryParse() vs Parse()).
There is obviously a small bit of overhead with parsing but its negligible compared to all the logic you would need to get the proper string manipulation.
Fiddle here
Parse the string as DateTime. Then run ToString with the format you desire.
var a = "1/1/2018";
var date = DateTime.Parse(a);
var result = date.ToString("ddMMyyyy");
You can use ParseExact to parse the input, then use ToString to format the output.
For example:
private static void Main()
{
var testData = new List<string>
{
"31/04/2018",
"01/03/2017",
"10/11/2018",
"12/11/2123",
"1/1/2018",
};
foreach (var data in testData)
{
Console.WriteLine(DateTime.ParseExact(data, "d/m/yyyy", null).ToString("ddmmyy"));
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
You didn't specify whether these are DateTime values or just strings that look like date time values. I'll assume these are DateTime values.
Convert the string to a DateTime. Then use a string formatter. It's important to specify the culture. In this case dd/mm/yyyy is common in the UK.
var culture = new CultureInfo("en-GB");//UK uses the datetime format dd/MM/yyyy
var dates = new List<string>{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};
foreach (var date in dates)
{
//TODO: Do something with these values
DateTime.Parse(date, culture).ToString("ddMMyyyy");
}
Otherwise, running DateTime.Parse on a machine with a different culture could result in a FormatException. Parsing dates and times in .NET.
I am getting the dateTime value in the format 2014-03-11T14:10:46+11:00.
I need to change this into the format 20140311141046+11:00.
The method I am using right now is:
private string changeDateFormat()
{
DateTime dt = Convert.ToDateTime("2014-03-11T14:10:46+11:00");
return dt.ToString("yyyyMMddHHmmss");
}
It seems to be working fine but with one catch.
Instead of showing the output like 20140311141046+11:00,
the output is 20140311084046.
I think I need to pass the timezone too while converting to string. But I am blank on how to do that.
PS: This +11:00 is dynamic can can change in the input. Please suggest a generic solution/approach.
Since you parse it to DateTime you lost the offset part.
I would parse it to DateTimeOffset instead of DateTime and use K format specifier with it's format like;
var str = "2014-03-11T14:10:46+11:00";
var dto = DateTimeOffset.Parse(str);
return dto.ToString("yyyyMMddHHmmssK");
returns
20140311141046+11:00
I want to change the DateTime for MySQL in C#.
My MySQL database only accept this format 1976-04-09 22:10:00.
In C# have a string who have a date value:
string str = "12-Apr-1976 22:10";
I want to convert for MySQL then it look like:
1976-04-12 22:10
How I can change them or how other programmer do this by using dd mm hh yy method? Can anyone tell me about them?
Keep in mind that you can hard-code ISO format
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
or use next:
// just to shorten the code
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "1976-04-12T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "1976-04-12 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
and so on
If your string format for the DateTime is fixed you can convert to the System.DateTime using:
string myDate = "12-Apr-1976 22:10";
DateTime dateValue = DateTime.Parse(myDate);
Now, when you need it in your specific format, you can then reverse the process, i.e.:
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm");
edit - updated code. For some strange reason DateTime.ParseExact wasnt playing nice.
I would strongly suggest you use parameterized queries instead of sending values as strings in the first place.
That way you only need to be able to convert your input format to DateTime or DateTimeOffset, and then you don't need to worry about the database format. This is not only simpler, but avoids SQL injection attacks (e.g. for string values) and is more robust in the face of database settings changes.
For the original conversion to a DateTime, I suggest you use DateTime.ParseExact or DateTime.TryParseExact to explicitly specify the expected format.
This works for me:
1.Extract date from oracle data base and pass it to variable
string lDat_otp = "";
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "";
}
else
{
lDat_otp = rw_mat["dat_otp"].ToString();
}
2.Conversion to mysql format
DateTime dateValue = DateTime.Parse(lDat_otp);
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm");
3.Pass formatForMySql variable to procedure or to something else
I have two fields:
string date1 = "04/26/10";
string date2 = "04/25/10";
How can I compare these two fields like so?:
if (date2 <= date1)
{
// perform some code here
}
Can this be done without first converting the fields to a separate date-type variable?
EDIT: I should mention that these values are coming from a database table where the date values are in a string format to begin with. Old legacy code...
No, but it is not difficult to convert to a date in C#.
if ( DateTime.Parse(date2,CultureInfo.InvariantCulture) <= DateTime.Parse(date1,CultureInfo.InvariantCulture))
{
// perform some code here
}
CultureInfo depends on the format the string dates have in the legacy DB. See: DateTime formats used in InvariantCulture
If your dates are actually stored as strings in the database, it seems like you can't be sure they'll be in a valid format before parsing. For that reason I'd suggest a small variation on jle's answer:
DateTime d1, d2;
if (DateTime.TryParse(date1, out d1) &&
DateTime.TryParse(date2, out d2) &&
d2 <= d1)
{
// perform some code here
}
else
{
// strings didn't parse, but hey,
//at least you didn't throw an exception!
}
At the very least you need to pick apart the strings in order to compare them in the right order.
If you want to leave them as strings, then you need to reorder them with LARGEST->SMALLEST units, so this:
yyyy/mm/dd
can be compared directly, but not the format you have. With your format, you need to split it, and either recombine it like above, or compare the individual pieces in the right order.
Having said that, it is rather easy to convert the strings to DateTime using DateTime.ParseExact.
Generally it is a bad idea to compare date as strings.
But if your strings are in the same format (e.g. yyyy/mm/dd means years, then monthes then days) then the comparison may be valid.
It could be done with string manipulation, but it would come down to effectively comparing three sets of integers, which as strings would induce more overhead than converting to datetimes. Why would you want to do that?
No. Let the .net framework sort that out for you. It will correctly identify the user date settings and format (using system settings, current thread) and determine which is the month, year and day - especially if that data comes from eg a sql server.
It's preferred to have the date formatted before doing the comparison. Depending in your cultureinfo, the safest way to compare dates is to format the date string to "yyyy-mm-dd".
DateTime d1, d2;
string date1 = "04/26/10";
string date2 = "04/25/10";
d1 = DateTime.Parse(date1.ToString("yyyy-MM-dd"));
d2 = DateTime.Parse(date2.ToString("yyyy-MM-dd"));
if (d1 > d2)
{
//do something
}
Best practice is to avoid comparing date as string types and compare with the official DateTime object of C#.
If your use-case requires the comparison using string objects then:
1st, make sure the date string format is yyyymmdd as recommend by Lasse V. Karlsen.
2nd, use the string method CompareTo to compare between the dates.
Here's how the method works in your case (Used C# Online Compiler to test this):
using System;
public class Program
{
public static void Main()
{
string fmt = "yyyymmdd";
string min = "20201206";
string max = "20210810";
Console.WriteLine(max.CompareTo(min)); // Output : 1
Console.WriteLine(min.CompareTo(max)); // Output : -1
string same1 = "20001212";
string same2 = "20001212";
Console.WriteLine(same1.CompareTo(same2)); // Output : 0
Console.WriteLine(same2.CompareTo(same1)); // Output : 0
// Summary:
// 1 = Greater than string param
// -1 = lesser than string param
// 0 = equals to string param
}
}
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