Datetime Conversion in C# - c#

I receiving dates in the USA standard format mm/dd/yy.
I can upload to MySQL only in the format of yyyy-MM-dd.
How can you convert mm/dd/yy format to yyyy-MM-dd format in C#?

You could parse it and then format it. (DateTime.ParseExact, DateTime.ToString)
However, you shouldn't have to reformat for MySQL's benefit, and it suggests your database access is inappropriate:
Your database column should be a DATETIME column or something similar, if you're storing dates in it
Your database code shouldn't be including the value as a string at all. It should be passing it as a parameter with a DateTime value
So using parameterized SQL, you should just need to parse (e.g. using DateTime.ParseExact), then pass it up as a DateTime:
DateTime date = DateTime.ParseExact(text, "mm/dd/yy",
CultureInfo.InvariantCulture);
command.Parameters.Add("#Foo", MySqlDbType.DateTime).Value = date;

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx ... please check here. you can convert the date format in C#

You can use MySQLs STR_TO_DATE(str,format) function. Or you can use string formatting in c#

Something like this should work:
DateTime dt = Convert.ToDateTime(dateString);
string newDateString = dt.ToString("yyyy-MM-dd");

Related

Convert System DateTime to specific format. eg:(yyyyMMdd hh:MM:ss)

I have problem in converting system datetime format to specific format.
for eg: DateTime dt=new DateTime();// It will return 11/15/2016 10:23 AM as per my system format.
But I have to convert into this format-- 20161115(yyyyMMdd hh:MM:ss). I can able to achieve this using `DateTime.Now.ToString("yyyyMMdd hh:MM:ss")? .
But its returning String format. I want in DateTime format.
DateTime as an object has no format. It contains the information as an internal numeric valus and is only formatted to string representation by your IDE or code. You don't change the format for it.
Only when you want to output it somewhere you set the format and you get a string for it.
Your DateTime is an object. That means the values are saved into its properties shown below.
If you want the DateTime to display in a different format than the default format then you use the ToString(yourFormat) method to format it. That will not change the data or the position of the properties if thats what you are expecting. (the term position of the properties itself is meaningless)
Its just representation. Just like how you have data in you database as tables but in UI you show it as a fancy HTML.
Internally the object saves data into each property and provides a default representation of it DateTime.Now.ToString(), And only when you dont want the default DateTime format you have the flexibility to format it into your choice.
So if your idea was to use this string date time for any code logic then you will just parse it into DateTime object by giving it the format the string is in like
DateTime date = DateTime.ParseExact(strDate, "yyyyMMdd hh:MM:ss", CultureInfo.InvariantCulture)
Now your string data is parsed into object and you can fetch the values as
date.Date , date.Millisecond etc
Here you go:
string str = DateTime.Now.ToString("yyyyMMdd hh:MM:ss");
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd hh:MM:ss", CultureInfo.InvariantCulture);
DateTime is a class with various properties and methods associated with it. You can't really return a DatTime object in a different "format" - it is just a representation of a point in time. You can however, represent a DateTime object as a stirng foramtted in a specific way. So what you are doing is correct:
DateTime.Now.ToString("yyyyMMdd hh:MM:ss")
Do this when you need to display the DateTime in a readabel format, such as in a log file or on a UI. If you need to pass a DateTime as a parameter, pass the entire object, not just a string representation of it.
DateTime.ParseExact(dateString, "yyyyMMdd hh:MM:ss", null);

Is there a way to format a date time object?

So last week, the way our application worked was that the back-end team was storing dates as a string in YYYY-MM-DD formats. This week, they changed it to be a DateTime object instead of a string. So now I'm just creating a DateTime object from the string value on this particular DateTime control we use.
So basically with our custom control , it was like this:
mySearchModelObject.fromDate = myDateRangeControl.Values[0]; //string
mySearchModelObject.toDate = myDateRangeControl.Values[1]; //string
Now it's more like this:
DateTime fromDate, toDate;
DateTime.Tryparse(myDateRangeControl.Values[0], out fromDate);
DateTime.Tryparse(myDateRangeControl.Values[1], out toDate);
mySearchModelObject.fromDate = fromDate;
mySearchModelObject.toDate = toDate;
But searching with the same date range as last week yields different results from the DB.
I'm wondering if it's because our dates were "YYYY-MM-DD" as strings, but now it's getting a date time object in whatever the system's format is + the time itself.
So is there a way to format my DateTime object to still have it in the same YYYY-MM-DD format?
Use DateTime.TryParseExact and provide "yyyy-MM-dd" as format string.
See http://msdn.microsoft.com/en-us/library/h9b85w22
you can do fromDate.ToString("yyyy-MM-dd") to have a date formatted as YYYY-MM-DD
see msdn on standard and custom datetime format
see demo https://dotnetfiddle.net/NZz0HG
also if mySearchModelObject.fromDate is of type object, you can assign a DateTime or a string, no compiler warnings/error.
But when is used, maybe with mySearchModelObject.fromDate.ToString() you get a different result, before was '2014-12-31' and now 12/31/2014 12:00:00 AM

How to Convert String Date in DateTime form in ASP.NET C#

I have a string Date which is coming from Database I need to parse or convert that String Date in DateTime form. Sharing the data and code as of now sharing the date which is coming from DB
String Date="7/19/2010 7:34:43 AM";
// I am parsing in DateTime form by below code
Date= DateTime.Parse(Date).ToString("yyyy-MM-dd HH:mm:ss.fff");
But I am getting the error while parsing with existing code as String was not recognized as a valid DateTime.
Can anyone please share some info how can I resolve this error so that I wont receive any exception
Note
Issue with my code is the date which is coming from Database is not a valid string type that's why I am getting the error string is not recognized as valid datetime
You should do, using DateTime.ParseExact
DateTime dt = DateTime.ParseExact("7/19/2010 7:34:43 AM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
DateTime.ParseExact(yourstring, "yyyyMMdd_HH:mm:ss.fff", new CultureInfo("en-US"));
Will solve your issue.
For reference follow :
Date Time Parse
Date Time Parse Exact
Either you can use
DateTime.ParseExact or DateTime.TryParseExact
This will allow you to specify specific formats.
I prefer the TryParseExact as they provide good coding style for the casing error.

DateTime suggestions with string format

I'm making a query which compares two DateTime values in SQL Server. The format of DateTime in SQL server is this:
2010-09-20 00:00:00.000
I'm using Entity Framework and let me tell you the problem I'm facing now.
When I'm comparing a DateTime value in Entity Framework, the attribute must be the same as the database which means that must be DateTime. The date comes from a post and that means that is a string. The problem here is, how can I convert them into DateTime and be the same format as it is in the database?
The user's input comes as a string and what I do is this:
DateTime start_date = Convert.ToDateTime(postValueHere);
But the value is not as expected:
2010/20/46 12:00:00 am
So, I give a format to it:
string format = "yyyy-MM-dd 00:00:00.000";
string date = start_date .ToString(format);
But now the value becomes as a string, which means that I cannot compare the value with Entity Framework:
db.Product.Where(x=>x.START_DATE== date)//error, cannot compare datetime with string.
How can I convert the user's input to the same format as it is in SQL Server and then to DateTime?
you can try with DateTime.TryParseExact() as :
DateTime start_date;
DateTime.TryParseExact(strDate, "yyyy-MM-dd hh:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out start_date);
Console.WriteLine(start_date);
you can check here for more custom formats.
If you are using EF to get that date value from the database, it should end up in a property with a DateTime type. This value is just a DateTime struct, without any format.
When you inspect the parsed date from the post, the debugger uses a .ToString() on the value, to get a string that it can display. It's still a DateTime struct without any format!
So just compare the DateTime values, without worrying about formats.

Help converting a string date to a DateTime

I'm using the Ajax control toolkit calendar extender on a textbox with a submit button. Simple.
The debugger shows that the text is properly being transferred to calling method, but this line of conversion code converts textbox text to 1/1/0001 12:00:00 AM. The text box date is this: 4/15/2011
DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);
What am I doing wrong?
You should use the DateTime.Parse() method:
DateTime txtMyDate = DateTime.Parse(txtDate.Text);
As mentioned you can also use DateTime.ParseExact() using a similar syntax as shown:
DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
[string format],
[IFormatProvider provider]);
Parse vs ParseExact:
Parse() - assumes the data is valid and does its best to fit it into the type, forcing things that seem vaguely ridiculous when a developer has a chance to invoke common sense.
ParseExact() - only allows the exact format specified and will throw on any variation.
Source on Parse vs ParseExact
There are many ways to convert text to a DateTime, try this one:
DateTime txtMyDate =
DateTime.ParseExact(txtDate.Text, "M/d/yyyy", CultureInfo.InvariantCulture);
Edit: forgot the culture info argument
Use DateTime.ParseExact to extract your date value from a formated date string:
DateTime dateValue =
DateTime.ParseExact(stringDateValue, "M/d/yyyy",
CultureInfo.InvariantCulture);
Try
DateTime instance = DateTime.Parse( txtDate.Text ) ;
which is [somewhat] flexible about what it will accept. Alternatively, DateTime.ParseExact() will give you move control over the conversion.

Categories

Resources