Possible to convert string date to mysql DateTime? - c#

I am working on a program that gets a list of file names from a directory, then parses the file names into individual variables (strings) and converts it into something that can be submitted to a mysql database that will the later be queued for searches.
In those file names contain a 4 digit year, 2 digit day, 2 digit month, 2 digit hour, and 4 digit minute (##AM/PM), followed by 2 numbers that can be between 3 and 11 digits.
I have parsed the filename and formatted the date and time info into the following string: YYYY/DD/MM HH:MMAM or YYYY/DD/MM HH:MMPM (only "AM" and "PM" changes on minutes).
EX: 2014/24/12 02:50PM
How can I convert the string into DateTime to submit into a MySql database.

The built-in STR_TO_DATE() function does what you need.
STR_TO_DATE('2014/24/12 02:50PM', '%Y/%d/%m %h:%i%p')
gives the result you need. You can look up the format codes here.

Using DateTime.ParseExact will do the trick to get it into .net's DateTime object:
string s = "2014/24/12 02:50PM";
DateTime dt;
DateTime.TryParseExact(s, "yyyy/dd/MM hh:mmtt", new CultureInfo("en-US"), DateTimeStyles.None, out dt) ;
Console.WriteLine(dt.ToString());

Related

MM-dd-yyyy to Julian yyddd

I am trying to get a label to display the Julian date in a specific format. The last two digits of the year then the day in the year, so for example January 1 2021 would be 210001. I am having difficulty getting it to display both of these values attached and making the day slot have 3 values instead of 2.
This is what I have.
This just gives the day of the year but still not as a 3 digit day so it shows 1 as 1 instead of 001 which is my goal
Any help would be appreciated! :)
Unfortunately the date time formats do not include anything for day of the year so you'll have to create this yourself. You can format a number to have leading zeros using the D format where you specify the length you want. You can however use the date formats to get the last two digits of the year. So the following should give you the desired formatted string for a date.
public string ToYYJJJ(DateTime date)
{
return date.ToString("yy") + date.DayOfYear.ToString("D3");
}

Unable to convert from string to datetime C#

I am trying to parse a string to Datetime, but it is not working and giving an error:
"String was not recognized as a valid DateTime."
The string is perfect.
Here is the code:
string deliv = DeliveryDateTextBox.Text;
string[] delivday = deliv.Split('-');
int year, month, day;
int.TryParse(delivday[0], out day);
int.TryParse(delivday[1], out month);
int.TryParse(delivday[2], out year);
string dtt = day + "/" + month + "/" + year;
DateTime datet = DateTime.ParseExact(dtt, "dd/MM/yyyy", null);
jobcard.DeliveryDate = datet;
I debugged the code and it is giving {01-01-0001 12:00:00 AM} on datet.
Besides the fact that you should be using new DateTime(year, month, day), or even DateTime.TryParseExact(deliv, "d-M-yyyy", .... ) on the original string...
Your call to DateTime.ParseExact() is failing because your input string has single-digit day and/or single-digit month, while your pattern dd/MM/yyyy demands double digits for both.
This can be fixed by using d/M/yyyy for the pattern, it will accept single and double digits. But please don't, see the first paragraph!
You over complicated things in this code.
Manually parsing the string to extract int values of day, month and year just to recombine them into a new string and parsing it makes no sense.
Simply try to parse the original string:
DateTime datet;
if(DateTime.TryParseExact(
DeliveryDateTextBox.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out datet))
{
// string was successfully parsed to dateTime.
}
There is no "perfect" DateTime String. How you can can/should represent a DateTime is dependent 100% on the CultureFormat of Windows, which can be totally different even within a langauge: For example en-gb and en-us disagree on what the decimal, thousand seperator are and in which order the date components should be listed.
Your whole code does not make a lot of sense. It seems you have some disjointed textboxes where the user inputs the day, month and year seperately. Then you parse them to int. Then you turn them into a string. Then you try to parse the string.
And at no point do you even check if the original user inputs are valid. That original parsing to Int might already fail. So you might try to parse 0/0/0 into a DateTime. To which your output is actually the perfect answer. And then there is stuff like anything before 1800 or so being literally not on the Gregorian calendar.
If you want the user to input a date, use a DatePicker element. Every GUI technology I know of has one. They give you DateTimes as return value. Do not try your custom workaround.

Date parsing from string to DateTime in c#

I am exporting date values("24/11/2016") from excel file to SQL database table in C#.NET. I am using the following code into my function to parse the date values from string to Datetime. But it is not working. I tried to debug it but when it comes on that line, it's terminating. Anybody know what is the problem.
var date = row["Date"].ToString();
DateTime dates;
string format = "MM-dd-yyyy";
if (!DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dates))
{
continue;
}
else
{
dates = DateTime.Parse(date); //terminating at this line
}
Your format should be dd-MM-yyyy as you have 24/11/2016 as date, you can learn more about string formats in this MSDN article Custom Date and Time Format Strings
Change
string format = "MM-dd-yyyy";
To
string format = "dd-MM-yyyy";
Edit based on comments by OP - Storing formatted date in SQL server
The DateTime is stored in a SQL server in standard format that is not in fact the presentation format we see like "dd-MM-yyy". This article Solving the Datetime Mystery explains the internal SQL server format.
Excerpt from Solving the Datetime Mystery
So how does SQL Server internally store the dates? It uses 8 bytes to
store a datetime value—the first 4 for the date and the second 4 for
the time. SQL Server can interpret both sets of 4 bytes as integers.
For the date portion, the value SQL Server stores is the number of
days before or after a base date of January 1, 1900. Because of this
storage protocol, SQL Server assumed the date of January 1, 1900, when
I didn't supply the date in my first example. SQL Server internally
stored a value of 0. A negative number represents a date earlier than
January 1, 1900.
SQL Server stores the second integer for the time as the number of
clock ticks after midnight. A second contains 300 ticks, so a tick
equals 3.3 milliseconds (ms). You can see the values for days and
clock ticks by converting a datetime value to a binary(8) value and
using the substring function to extract each set of 4 bytes. The code
in Figure 3 then converts each set of 4 bytes into an integer.
Finally i did it using the following code:
string format = "dd/MM/yy";
if (!DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None,out dates))
{ continue; }
else
{ dates = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture); }
String datetime = dates.ToString("yyyy-MM-dd");
Thanks to all.

Parse Simple DateTime

DateTime dt = DateTime.ParseExact("1122010", "Mddyyyy", System.Globalization.CultureInfo.CurrentCulture);
Throwing this exception: String was not recognized as a valid DateTime.
I'm sure it's the lack of a leading 0 in the month. What's the correct format string?
I suggest using the format "MMddyyyy" and ensuring your input parameter has at least 8 characters. Example:
DateTime dt = DateTime.ParseExact("1122010".PadLeft(8, '0'), "MMddyyyy", System.Globalization.CultureInfo.CurrentCulture);
If you are using a data source with the leading 0 missing for the month, this will add it where required.
The problem is that you are not giving ParseExact enough information to work with.
"M" means a 1 or 2 digit month. But your string starts with "1122". Is that January 12th or November 22nd?
The only solution, as Anthony shows, is to pad with a 0 when needed.
The single "M" format string is unacceptable because not all months can be uniquely represented with a single digit or character. As previously suggested, you will have to use "MMddyyyy" and pad the left string when necessary.

Format .NET DateTime "Day" with no leading zero

For the following code, I would expect result to equal 2, because the MSDN states that 'd' "Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero.".
DateTime myDate = new DateTime( 2009, 6, 4 );
string result = myDate.ToString( "d" );
However, result is actually equal to '6/4/2009' - which is the short-date format (which is also 'd'). I could use 'dd', but that adds a leading zero, which I don't want.
To indicate that this is a custom format specifier (in contrast to a standard format specifier), it must be two characters long. This can be accomplished by adding a space (which will show up in the output), or by including a percent sign before the single letter, like this:
string result = myDate.ToString("%d");
See documentation
Rather than using string formatting strings, how about using the Day property
DateTime myDate = new DateTime(2009,6,4)
int result = myDate.Day;
Or if you really needed the result in string format
string result = myDate.Day.ToString();
If you are looking to get a specific date part out of a date object rather than a formatted representation of the date, I prefer to use the properties (Day, Month, Year, DayOfWeek, etc.) It makes reading the code a bit easier (particularly if someone else is reading/maintaining it that doesn't have the various formatting codes memorized)

Categories

Resources