DateTime format - one digit day not recognized - c#

I need to read a String in the following format: "6102015" (meaning October 6th, 2015) and turn it into DateTime objects.
I tried the following code, which did not work:
DateTime.ParseExact("6102015", "dMyyyy", CultureInfo.CurrentCulture);
But when I tested the code using the date string with an extra 0, it worked.
DateTime.ParseExact("06102015", "dMyyyy", CultureInfo.CurrentCulture); // works correctly
Is there a way to read this date format without having to add the 0?
I thank you in advance for any help.

Is there a way to read this date format without having to add the 0?
Adding a 0 is the least of your worries, IMO. That takes one line of code.
Assuming you've got a copy of the database or something you can alter, effectively, I would:
Create a field of a date/time type, or if you must use a string, do so but use an ISO-8601 format (yyyy-MM-dd)
Parse all the values which are already 8 characters
Parse all the values which are 6 characters by inserting two 0s (so abcccc becomes 0a0bcccc)
For each remaining value, of the form abcyyyy:
Try parsing it as 0abcyyyy
Try parsing it as ab0cyyyy
If only one parse worked, store that result in the new column
Now look at all the remaining rows (i.e. the ones you haven't populated with a "known good" value
You may be able to use other data (such as insertion order) to work out which is the "right" parse...
You may not - in which case you need to decide what to do

Related

DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") gives different formats for different users

I assumed that ToString("yyyy/MM/dd HH:mm:ss") will force the string to be formatted with '/', but I can see that every device gets different formats. How can I force it to be saved with '/'?
Good example-
2021/10/06 18:05:53
Strange examples I see in my DB from different users-
2021-10-06 23:48:37
2021.10.12 12:41:42
2021. 10. 06 19:17:23 ('.'+ space after)
2021.10.13 19.18.16
One solution is to replace every -, . and . to /, but this only solves the strange examples I found. What if there are others?
/ in a format string means "the culture-specific date separator". If you want the literal forward-slash, quote it (and the colons, to avoid the use of a custom time separator):
ToString("yyyy'/'MM'/'dd HH':'mm':'ss")
Alternatively - and probably better - use the invariant culture. Not only will that use / as the date separator, but you won't need to worry about a culture having a different default calendar. (It'll always use the Gregorian calendar, which is presumably what you want.)
Even better, use an ISO-8601 format - you're already using a "slightly unusual for humans" format of year-first, so you might as well go the whole hog and go with the standard format for dates and times.
Sample code:
String text = dateTimeValue.ToString(
"yyyy-MM-dd'T'HH:mm:ss",
CultureInfo.InvariantCulture);
This is also the sortable standard date/time format so you can simplify the code significantly:
String text = dateTimeValue.ToString("s");
(That format always uses the invariant culture.)
That's if you really need to format the string at all, though. If you're saving it in a database, I'd advise you to:
Use an appropriate type in the database, e.g. DATETIME
Store it using a parameter (specifying the value just as a DateTime), not formatted text
If you do both of these, you'll avoid oddities like this.
Another solution that I can think of is creating a new function that creates a date
DateTime date= DateTime.UtcNow;
And extracting manually and splitting the date to a few strings (year,month,day,hour,month,seconds)
string year = date.Year.ToString(); string month = date.Month.ToString();...
and building a string out of it in the right format,
string newDate= year + "/" + month + "/" + day + " "+ hour+":"+ minute+ ":"+seconds;
that way I can be sure it's always one format that I'll decide on
How about storing the date as a number, eg unix time - DateTimeOffset.UtcNow.ToUnixTimeSeconds() or (DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds - it's a lot simpler and cheaper to store a number than a string
Also wanted to point out that the only date I've
seen you store so far is UtcNow (as written in your answer) - fire base does appear to have a solution for that in that you can send ServerValue.TIMESTAMP and it will cause fb to store the unix time as the server sees it.
My take away from this (never used fb) is that that's how they store dates so perhaps it makes sense to follow :)

String was not recognized as a valid DateTime from SQLite file

I have a program, that puts the .txt files to a database file (im using system.data.sqlite NuGET package). I have yyyy.MM.dd format set on my Pc, and it's used by the database too, however I still get the above mentioned error.
An additional info, that could help, is that when I set the table's appropriate column to a simple string it's working as normal, but as soon As I set it to date it gives me this exeption.
Can someone please help me?
You seem to be mixing up how a type is formatted into text with the type itself. If a column is typed as date, then its expecting a date, not a text conforming to whatever date format you have in mind.
Its the same is if you try to do the following:
DateTime date = "01.01.2020";
This won't compile, because string, nevermind if it represents a valid formatted date, and DateTime are two altogether different types.
If you are reading from a text file, you first need to convert the formatted string representations to their corresponding DateTime. See DateTime.TryParse method on how to do this. Once you have valid dates in your hands, try pushing those to the DB.

Date type in MySql

I'm new to MySQL and C#.
I stored certain values in a column with data type Date. I did not want the time, only the date to be stored.
On viewing these values using phpMyAdmin or MySql command line, I see them in the format:
YYYY-MM-DD
However, when I retrieve these values in to my web application, they are displayed in the following format:
YYYY-MM-DD HH:MM (the time is specifically 12:00).
Why does this happen? And how can I prevent this from happening?
when you store in C# your date field, you use DateTime object. In this object when you don't specify the time part will be put a default value depends on Globalization.
You can study how DateTime works here
You can convert the date to the format you like when you fetch the data, using date_format():
select date_format(datecol, '%Y-%m-%d')
This returns the value as a string.
You shouldn't retrieve the value as a string from mysql. Why? Because if you ever need to do any operations on that value, such as adding a day, then you will need to parse it back into a DateTime again. String parsing can be slow, and when it comes to dates they are prone to errors like misinterpretation of mm/dd/yyyy and dd/mm/yyyy formatting.
The problem you have is that .NET does not have just a Date type. It only has a DateTime type. So loading a MySQL DATE type, is going to get a DateTime with the time portion set to midnight.
There's no direct problem with that, except on how are outputting the result. If you just call .ToString() without any parameters, or you implicitly use it as a string, then you are going to get a result with the full date and time. You simply need to provide a parameter to indicate what formatting you want.
Without any parameters, you are getting the General "G" format. This is explained in the documentation here.
In other words:
yourDateTime.ToString() == yourDateTime.ToString("G")
You can read about all of the other formats available, here and here.
In particular, if you just want the date, then you probably want to do this:
yourDateTime.ToString("d")
Based on your comments, you should be doing this instead:
MySQL Query:
SELECT Gbstartdate FROM TblGbDef
C#:
DateTime gb_start_date = (DateTime) datareader[0];

Convert 2012-06-28T14:30:00-04:00 to yyyyMMddTHHmm format in C#

I want to convert a date in c# like 2012-06-28T14:30:00-04:00 in to "yyyyMMddTHHmm" format both dates are in string.
string currentDate="2012-06-28T14:30:00-04:00";
string requiredDate="yyyyMMddTHHmm"
When i am trying to convert this date with Convert.ToDateTime() then C# return "20120629T0000-04:00" but this is not correct date.
Have a look at the Standard Date and Time Format Strings (MSDN). I guess it might be enough to use just the ToString() method on your DateTime instances.
Possibly you might need to specify CultureInfo (MSDN here) in the appropriate overloads of the convert methods. Possibly the server and client applications are in different cultures and/or timezones.
DateTime.Parse("2012-06-28T14:30:00-04:00").ToString("yyyyMMddTHHmm") produces value you may want.
Note that changing value from absolute ISO8601 format to local ISO8601 format should be done carefully as it changes meaning of the value and often value itself.
Please make sure which of the following options you really want (and adjust code accordingly):
simply drop time from the value. Will produce semi-random time if values are coming from different time-zones.
always move value to a given timezone and make it local to that timezone.
always move value to current timezone and make it local to current timezone
Or maybe you are looking for something else altogether.
I'm not sure this is the format you are trying out
string currentDate="2012-06-28T14:30:00-04:00";
DateTime.Parse(currentDate).ToString("o")
This will give you 2012-06-29T00:00:00.0000000+05:30

C# Regex, formatting a time

I'm making a timecard program, where the user enters the start time, end time, and project name. They can click "Add" and it adds the entered details to a listbox.
I don't allow the data to be added unless the start time and end time are formatted like this: 08:14am It gets annoying, though, having to enter it exactly like that each time, so I decided to, via regexes, have it automatically format. So if you enter 8:14, it will change it to 08:14am. How can I accomplish this via Regex.Replace()?
If you have any other methods, don't hesitate to list them.
Edit 1: I also have other replacements in mind; for example 814 goes to 08:14am, and 8 goes to 08:00am
Edit 2: So Now I'm using this code:
string[] formats = { "h:mm", "h", "hh", "hmm", "hhmm", "h:mmtt", "htt", "hhtt" };
DateTime dt = DateTime.ParseExact(t.Text, formats, new CultureInfo("en-US"), DateTimeStyles.None);
t.Text = dt.ToString("hh:mmtt").ToLower();
And it replaces some things, like h:mm but not others like h.
Have you looked at DateTime.Parse? It accepts "08:14am", "8:14"[1] and other variants, and returns a DateTime set to 8:14 am on today's date.
[1] In the UK culture at least -- consider providing a CultureInfo parameter depending on whether you want to pay attention to the user's local format preferences, or adopt a fixed format.
EDIT I also have other replacements in mind; for example 814 goes to 08:14am, and 8 goes to 08:00am
Take a look at DateTime.ParseExact: you can provide an array of valid time formats (such as "hh:mm", "hmm", "h" etc.)
Coming at it from a completely different direction, how about using a mask on the input?
For example, there are a number of JavaScript and jQuery tools available to do this.
Using this approach retains some user control over the input, and lets the user see their input.
have you considered using a DateTimePicker? Making the user write the time looks like more of a hassle.
See e.g. http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.aspx
I think regex are overkill for this. Why not simply append the "am" at the end, in case nto already added is a 2 line code in case you are working with strings in the method.
I would recommend against using regular expressions if possible (as others have said, it seems like overkill) and try using datetime formats. See here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
The "HH" format tag will format the hour as a 24-hour time from 00 to 23. Traditionally, 12 hour times are not zero-padded to the left, but 24 hour times are (at least as often as I see them), probably to avoid confusion between 1800 and 0800 . Alternatively, if you don't want 24 hour times, you could probably just left-pad the hour part of the string with a zero to up to 2 digits.
EDIT:
Based on your new requirements, I'd say write a simple parser to let users input "814" meaning "08:14 AM" and make use of the time-formatting functionality for display.

Categories