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.
Related
This question already has answers here:
Converting a String to DateTime
(17 answers)
Closed 3 years ago.
I want to convert string datetime to Datetime using C#. I am going to store datetime in sql database
The string in your example has an offset component so you can use DateTimeOffset:
var dateTimeOffset = DateTimeOffset.Parse("2012-08-16T19:20:30.456+08:00", CultureInfo.InvariantCulture);
From the linked docs:
The DateTimeOffset structure includes a DateTime value, together with
an Offset property that defines the difference between the current
DateTimeOffset instance's date and time and Coordinated Universal Time
(UTC).
just
DateTime date= DateTime.Parse(dateString);
Use DateTime.Parse("2012-08-16T19:20:30.456+08:00")
Use can use C# Interactive Windows to test it.
//string value of date
var iDate = "2012-08-16T19:20:30.456+08:00";
//Convert.ToDateTime(String)
//This method will converts the specified string representation of a date and time to an equivalent date and time value
var dateConversion1 = Convert.ToDateTime(iDate);
//DateTime.Parse()
//DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among text.
var dateConversion2 = DateTime.Parse(iDate);
//DateTime.ParseExact()
//ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.
var dateConversion3 = DateTime.ParseExact(iDate, "yyyy-MM-dd HH:mm tt", null);
//CultureInfo
//The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is a third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.
var dateConversion4 = DateTime.ParseExact(iDate, "yyyy-MM-dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture);
//DateTime.TryParse method
//DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture - specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
DateTime dateConversion5;
DateTime.TryParse(iDate, out dateConversion5);
These are few C# methods which can be used as a conversion string to DATETIME, make sure string is a valid string so that it allows you to convert.
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);
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
I am reading from excel file and save the content into database
one of the column contains length of video in this format
HH:mm:ss
I write this code so far
string time = oledbReader[6].ToString();
DateTime streamingTime = DateTime.ParseExact(time,
"HH:mm:ss",
System.Globalization.CultureInfo.CurrentCulture);
I am getting error:
String was not recognized as a valid DateTime.
I tried debug mode and I see the value :"30/12/1899 00:09:21" in the Variable time
when the value in the current execl column is:"00:09:21"
Where does the "30/12/1899" came from? Why is the string was not recognized as a valid DateTime?
Can I save only the format HH:mm:ss into sql server?
Try this, easy hack as my comment above.
string time = oledbReader[6].ToString().Split(" ".ToCharArray())[1];
DateTime streamingTime = DateTime.ParseExact(time, "HH:mm:ss",System.Globalization.CultureInfo.CurrentCulture);
or you could parse it as it is...
DateTime streamingTime = DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Since you didn't gave us any information about your CultureInfo, here with InvariantCulture;
string time = "30/12/1899 00:09:21";
DateTime streamingTime = DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(streamingTime);
Output will be;
12/30/1899 12:09:21 AM
Here a DEMO.
For more informations, check out Custom Date and Time Format Strings
Use a TimeSpan structure to hold a time value. A DateTime includes both a date and a time.
The problem is that excel not have time field and automatically convert time to date time field.
If course date is "empty" which means that it its a minimal date for excel - 30/12/1899
Moreover you don't have to invoke ToString methods because object is already a DateTime
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");