I'm having a huge issue with inputting DateTime into my MySQL db. MySQL reads datetime as yyyy-MM-dd HH:mm:ss while C# sees datetime as dd/MM/yyyy HH:mm:ss. I have tried two different examples and both doesn't work.
MODEL
public class DateAndTime
{
public DateTime DateTime { get; set; }
}
CONTROLLER
//I Have two examples that doesn't work.
var myDateTime = "2016-04-08 12:00:00" //this gives the error "cannot covert source 'string' to tartget type System.DateTime
var myDateTime = Convert.ToDateTime("2016-04-08 12:00:00") //this gives the error "Input string was not in a correct format."
var model = new DateAndTime
{
DateTime = myDateTime
};
So I'm stuck. I'ms sure someone out there has had this issue.
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
Check:
Converting a String to DateTime
https://msdn.microsoft.com/en-ca/library/cc165448.aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I have this issue because of the datetime format in my machine. If your desktop is configured like dd/mm/yy(the / symbol instead of -) then you have to replace - with / before converting. Please let me know
try this :
myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
myDateTime variable must be type DateTime.
or you can use this MySql function : STR_TO_DATE
STR_TO_DATE('4/8/2016 2:18:17 PM', '%m/%d/%Y %h:%i:%s %p')
Specifier Format here
Related
i have the following object that can be nullable at times follows
public string issued {get;set;}
The issued string looks like this: 2022/02/29 22:00:00 +00:00
I want to assign the issued variable to another variable as 2022/02/29 when its not null.
This is what i tried:
var item = new model() {
issuedDate=issued.IsNullOrEmpty() ? "" : issued.ToString("yyyy/mm/dd")
}
But it throws an error:
can not convert from string to system.IformatProvider?
How can I fix this?
I recommend using DateTime as helper with TryParseExact to determine if the source is a valid DateTime format. Via the DateTime helper variable you can then create any DateTime formatted strings you need to.
string issued = #"2022/02/29 22:00:00 +00:00";
string issuedDate;
DateTime dateTimeIssued;
if (DateTime.TryParseExact(issued, "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTimeIssued)) {
issuedDate = dateTimeIssued.ToString("yyyy/MM/dd");
}
Be aware that TryParseExact only works if the format is known to the system culture.
you can try for format;
string.Format("{0:yyyy/MM/dd}",issued);
this will be return 2022/02/29 for you
and you can look this page, for more information on DateTime format.
https://www.csharp-examples.net/string-format-datetime/
I have a datetime in string format with the Format ( 2019-09-19T18:00:54.110 )
I want to convert the above datetime format to UTC format (yyyy/mm/dd hh:mm:ss ) which is also a string format , I am not able to figure this out
Appreciate help !
This is what i have done so far ,
public string FormatDate(string inputDate)
{
System.DateTime strDate;
if (System.DateTime.TryParseExact(inputDate, "yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out strDate))
{
return strDate.ToString("yyyy/MM/dd HH:mm:ss");
}
return "INVALID DATE";
}
You need to specify the milliseconds as well, with the f format specifier. So you will end up with something like this:
yyyy-MM-ddTHH:mm:ss:fff
Well, c# has many amazing functions on DateTime. Simply try:
var time = DateTime.Parse("2019 - 09 - 19T18: 00:54.110");
var result = time.ToUniversalTime().ToString("yyyy/mm/dd hh:mm:ss");
And if you want to check the input data, add a try&catch block!
I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00
I have textbox asssociated with model class having value like
"03/28/2014".
I want to convert this to DateTime with 28/03/2014 format. I have tried following ways, but I'm not getting anywhere close...
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-US", true);
string date = timesheetModel.START_DATE;
string pattern = "dd-mm-yyyy";
DateTime dt=DateTime.ParseExact(date,pattern,theCultureInfo).
DateTime dt= Convert.ToDateTime(timesheetModel.START_DATE);
and also DateTime.Parse(date);
By this getting compile time error:
"String was not recognized as a valid DateTime."
I have tried also in modal class with Types like:
public string date{get;set;} // by this type not converting to datetime
public DateTime date{get;set;} // not able to access values to controller
Is there any other solution for this? Because the textbox value format is fixed.
I guess you should Use DateTime.ParseExact with the format "dd/MM/yyyy"
var result = DateTime.ParseExact("03/28/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture)
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
you can go though the below link for more information
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
hi i have datetime format in database like this
1/18/2014 4:14:52 PM (M/DD/YYYY h/mm/ss)
i convert it to ToLongDateString
string date = Convert.ToDateTime(myQuizOccurrence.occurred).ToLongDateString();
**result ->** **Sunday, January 12, 2014**
i want to convert back again that result date to become same format as database i wonder how to do it?
edited
so far i already try as #matt says using datetime instead string
DateTime dt2 = (DateTime) myDataGridView.CurrentRow.Cells[3].Value;
i already check it's have same format as datetime in database
but when i try to matching in query with this following code
Global.dbCon.Open();
string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = " +dt2+ "
ORDER BY ID";
Global.reader = Global.riyeder(kalimatsql2);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idku = Convert.ToInt32(Global.reader.GetValue(0));
MessageBox.Show(idku.ToString());
}
}
Global.dbCon.Close();<br>
it's give error result
Syntax error (missing operator) in query expression 'Occurred = 1/12/2014 4:18:59 PM'
what i'm missing?
The vast majority of databases you will interact with should be accepting either a DateTime or a DateTimeOffset type directly. You would not use a string when retrieving data from the database, nor when sending data back to it. Therefore, format is irrelevant.
My guess is you are doing something similar to this:
DateTime dt = Convert.ToDateTime(mydatareader["MyDateTime"].ToString());
Instead you should be doing this:
DateTime dt = (DateTime) mydatareader["MyDateTime"];
When you save it back to the database, you should be using parameratized inputs that will take the DateTime directly. If you're trying to concatenate a string to build an SQL statement, you're doing it wrong.
i have datetime format in database like this
The best practice is to store date and time information with DateTime or DateTimeOffset type.
To convert back your string to DataTime you can use this:
string str = "Sunday, January 12, 2014";
var dateTime = DateTime.ParseExact(str, "D", CultureInfo.CurrentCulture);
Note that you loss the time part when you convert it to long date.