How to convert dd/mm to Mysql Datetime format in c# - c#

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

Related

How to convert this date 2017-07-09T17:50:21.000-0500 | C#

when i run the below code,
string dt = "2017-07-09T17:50:21.000-0500";
DateTime date = Convert.ToDateTime(dt);
it gives me output as
7/10/2017 4:20:21 AM
where as i want my output to be
2017-07-09 17:50
update
the code #alexander-petrov gave worked
string dt = "2017-07-09T17:50:21.000-0500";
string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");
gives output
2017-07-09 17:50
but on inserting the same to database it is adding +5 hrs to the time and inserting as
2017-07-09 22:50
This is a Round-Trip format of a DateTime specified with a DateTimeKind.Local kind.
You need to decide if your program needs to be aware of time zones or not.
You could try parsing it while supplying the System.Globalization.DateTimeStyles.RoundtripKind or System.Globalization.DateTimeStyles.AdjustToUniversal parameter to the Parse method.
If you want take offset into account then use DateTimeOffset type.
string dt = "2017-07-09T17:50:21.000-0500";
DateTimeOffset date = DateTimeOffset.Parse(dt);
// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);
// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);
I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:
DECLARE #stringDate VARCHAR(30);
SELECT #stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE #xmlDate XML;
SELECT #xmlDate = CAST('' AS XML);
SELECT #xmlDate.value('xs:dateTime(sql:variable("#stringDate"))', 'datetime');
Results:
2017-07-09 22:50:21.000
Try:
string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

Convert date and time into Correct format to compare to current date

I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);

convert back datetime format toLongdatestring to (M/DD/YYYY h/mm/ss)

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.

Read Date Value from TextBox and Convert to Month and Year

i have a text-box in a detailview and the value of the text-box is a Date but it only shows the Month and Year and it is like this:November 2013 so i want to take this value and convert like this: 20131101. So as you can see, i would like the format to be YYYYMMDD but the day should always be 01 which is the first of the month. So how can i go from this November 2013 to this 20131101? here is my code and i know i have to convert from string to date first:
string myDate = ((TextBox)DetailView1.FindControl("InputDate")).Text.ToString();
Convert it:
TextBox txtInputDate = (TextBox)DetailView1.FindControl("InputDate");
DateTime dt = DateTime.ParseExact(txtInputDate.Text, "MMMM yyyy", CultureInfo.InvariantCulture);
then convert it to string again:
txtInputDate.Text = dt.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
C# is pretty good at parsing stringy dates, you could lean on the build it parsing:
string myDateString = ((TextBox)DetailView1.FindControl("InputDate")).Text.ToString();
DateTime myDate;
if (DateTime.TryParse(myDateString, out myDate)) {
// myDate now contains a proper .NET date.
}
Now you have a proper DateTime, you can output it in any format you like.
DateTime test = DateTime.Parse("November 2013");
Console.WriteLine(test.ToString("yyyyMMdd"));
Use the DateTime.ParseExact() method, like this:
var theParsedDate = DateTime.ParseExact(myDate, "MMMM yyyy",
CultureInfo.InvariantCulture);
Now you can use the parsed date however you wish, convert it to string, send it to database, etc.

how to convert time in string format into date time format using C#

i have textbox that accepts time format like this 12:40 PM but would like to convert it into time format like this 12:40:00 basically without the PM or AM. Here is what i have so far:
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
thanks
One option would be to parse into a DateTime and then back to a string:
string s = "12:40 PM";
DateTime dt = DateTime.Parse(s);
string s2 = dt.ToString("HH:mm:ss"); // 12:40:00
Be aware, however, that most operations work better with a DateTime versus a string representation of a DateTime.
First you should parse it to a DateTime, then format it. It sounds like your input format is something like hh:mm tt and your output format is HH:mm:ss. So, you'd have:
string input = "12:40 PM"
DateTime dateTime = DateTime.ParseExact(input, "hh:mm tt",
CultureInfo.InvariantCulture);
string output = dateTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
Note that:
I've used DateTime.ParseExact which will throw an exception if the parsing fails; you may want to use DateTime.TryParseExact (it depends on your situation)
I've used the invariant culture for both operations here. I don't know whether or not that's correct for your scenario.
I've used hh:mm, but you might want h:mm... would you expect "1 PM" or "01 PM"?
You don't parse seconds, so that part will always be 0... is that okay?
Since you are bringing it in as a string this is actually kind of easy.
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
DateTime dt = new DateTime();
try { dt = Convert.ToDateTime(StartTime); }
catch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }
StartTime = dt.ToString("HH:mm");
So you bring in your string, and convert it to a date. if the input is not a valid date, this will default it to 00:00. Either way, it gives you a string and a DateTime object to work with depending on what else you need to do. Both represent the same value, but the string will be in 24-Hour format.
Cheers!!

Categories

Resources