DateTime problem when day <= 12 - c#

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:
I have a bunch of date strings in cells that I'm pulling out such as:
03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.
While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.
For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00"
The others are all read and nicely provide me with a simple string of "27/05/2011".
I'm getting this info from Excel, using
((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()
If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.

If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.
Example:
var dateString = "03/05/2011";
var format = "dd/MM/yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
More information on custom Date and Time format strings can be found here.
EDIT: Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:
var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);

DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information.
The format of the string representation must match the specified format exactly.
String dateString = "15/06/2008";
String format = "dd/MM/yyyy";
DateTime result =
DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

That sounds like a localization problem. Try setting your locale implicititly. For example in WPF application it's something like:
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");

I have a bunch of date strings in cells that I'm pulling out such as:
No, you don't. You have a mix of strings that look like dates and dates that look like strings. This is an Excel issue, not a C# issue.
Not sure if you are creating the spreadsheet, or if you are getting it from somewhere else. But it the problem is that Excel attempt to parse text as it is entered in the cell. In this case, it is making some wrong decisions about the dates it finds.
If you enter a date like "03/05/2011", Excel will (incorrectly) parse it as March 5th, 2011, and store that as a numeric date code (40607). It then applies a date formatting to the cell (it uses m/d/yyyy on my machine).
If you enter a date like "31/05/2011", Excel can't parse it as a date, and it stores it as text.
To prove this, select the cells and go to Edit > Clear > Formats. All the "bad dates" will just show as numbers, all the rest will stay looking like dates.
You have a few choices:
Fix the data before its entered into Excel (prepend everything with a ' so its all entered as text, or make sure to create the spreadsheet on a machine that has the right date settings.)
Don't use the .Value.ToString() from Excel, just use .Text. This will ignore the bad parsing that Excel did, and should give you a consistent text value (from both types) that you can ParseExact with C#, per the other answers.
(2) is a lot easier, and if the spreadsheets already exist, may be your only choice.

The problem is because your Dates are being read as american culture or similar.
If you use the following you can specify the format you expect your dates to be in:use
DateTime result;
if(DateTime.TryParseExact("dd/MM/yyyy", out result))
{
// Got an English date
}

Related

Transforming string to an array of characters to extract and check date and ignore time

I have strings containing dates, like this one: "2020-03-10T12:53:02".
I have a CSV file full of dates. I want to select the date of 2020-03-10 only but I don't know-how while the time exists.
If you only need the string ignoring the time, and the format is always "yyyy-MM-dd", then simply do:
var date = "2020-03-10T12:53:02".Substring(0, 10);
If you need a DateTime ignoring the time info then:
var date = DateTime.Parse("2020-03-10T12:53:02").Date;
If incorrectly formatted dates are a possibility, then use TryParse instead of Parse.

Parse a date from an export of a lotus notes base

In a C# application, I have to parse an xml file which is an export of a lotus notes database.
The exports contains dates in this format :
<noteinfo noteid='6706' unid='6B6A3ADD41061773C12580F2004E8EB3' sequence='6'>
<created>
<datetime dst='true'>20170329T161803,39+02</datetime>
</created>
<modified>
<datetime>20171108T100439,39+01</datetime>
</modified>
<revised>
<datetime>20171108T100439,38+01</datetime>
</revised>
<lastaccessed>
<datetime>20171108T100439,38+01</datetime>
</lastaccessed>
<addedtofile>
<datetime dst='true'>20170329T163711,21+02</datetime>
</addedtofile>
</noteinfo>
I have to extract these dates into a .Net Datetime value.
However, I don't get what's this format. Trying to parse the date fails:
var created = DateTime.Parse("20170329T161803,39+02");
Throws
String was not recognized as a valid DateTime
How to parse this date format ?
The first part of the date, before the comma, is obvious. The second part is less. +02 probably match the GMT+02 timezone, but I don't get the 39
PS: I don't have control on the exports
Assuming ,39 are the milliseconds
var created = DateTime.ParseExact("20170329T161803,38+02", "yyyyMMddTHHmmss,ffz", CultureInfo.InvariantCulture);
Reference: DateTime.ParseExact
Try
var created = DateTime.ParseExact("20170329T161803,39+02".Remove(15), "yyyyMMdd'T'HHmmss",CultureInfo.InvariantCulture);
I'm not sure what the ,39+02 is in terms of a time - zone perhaps? I trimmed it off, but if you can describe what it is maybe it can be parsed
Edit:
Assuming that's milliseconds and timezone:
var created = DateTime.ParseExact("20170329T161803,39+02", "yyyyMMdd'T'HHmmss','ffz",CultureInfo.InvariantCulture);

Webtest - Using Dates as Context Parameters

I've created a webtest and have a CSV data source that contains a column with a list of short dates (MM/dd/yyyy)
I need to manipulate the parameter due to part of the web page I'm testing has a form parameter that needs it to be formatted as yyyyMMdd
When the date that is captured from the data source (ex: 02/12/2016), I noticed in the Context tab of my test run that the format to "2/12/2016 12:00:00 AM"
I've created a Request plug-in and added the following code:
public override void PreRequest(object sender, PreRequestEventArgs e)
{
base.PreRequest(sender e)
string CSVDate = e.WebTest.Context["<datasource date column>"].ToString();
DateTime dt = DateTime.ParseExact(CSVDate, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
e.WebTest.Context.Add("NewDate", dt.ToString("yyyyMMdd"));
}
This generates a String was not recognized as a valid DateTime error. I tried changing the format to MM/dd/yyyy, but I encountered the same error.
Does anyone know how the correct DateTime format I should be using?
The date-time as shown in the context is 2/12/2016 12:00:00 AM. This has only one digit for the month whereas the format specifier has MM which wants two digits. The date-time also contains the letters AM that are not matched by the format.
Modifying the format to be M/dd/yyyy HH:mm:ss matches the date-time 2/12/2016 12:00:00, but does not match the AM part. In theory the tt format specifier should match this, but it did not work for me.
Rather than using ParseExact you can use Parse and it works out the correct format. Using the following worked on the date-time string provided:
DateTime dt1 = DateTime.Parse(CSVDate, new System.Globalization.CultureInfo("en-US"));
The CultureInfo is needed because the input date has the month and the days the wrong way around.
However, the real problem is in the way CSV files are handled by the web test. It appears to read them using the same logic as Microsoft Excel uses when reading CSVs. Namely, if it looks like a date then convert it to a date. So any string matching dd/dd/dddd (where d is a digit) might be connverted to a date. (E.g. 15/15/2017 will not be converted because 15 is not a month number.) I recommend rewriting the CSV to format the input date differently, use something that Excel would not treat as a date. One option is to have the date in three columns of the CSV, so have explicit day,monthandyearcolumns. Another option is to add non-date characters to the string and format it correctly, eg asz20160212and then remove thezwithin the web test. Generally, I would advise to avoid the conversion of string toDateTime` then another conversion to a different string.

Datetime Formatting giving it a specific culture doesn't change how day is printed out

Is DateTime format strictly dependent on the language of the OS being used? Because the following doesn't work:
DateTime date = DateTime.Now;
var usCultureInfo = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine(date.ToString("dddd MM-dd-yy"),usCultureInfo);
I'd like the result to print out as Saturday, 06-29-2013 but the day gets printed out in Korean 토요일, 06-29-2013.
You are a victim of Composite Formatting overload for Console.WriteLine where you could pass Format string and a series of object to be inserted in the placeholders of the format string
You need to write in this way
Console.WriteLine(date.ToString("dddd MM-dd-yy",usCultureInfo));
and you get the right day text.
See the specs here DateTime.ToString(format, IFormatProvider)
Or simply you can use
string abc=date.ToString("dddd MM-dd-yy");

Datetime formats and JSON data in C#

I'm having an issue with date/time formats in ASP.NET/C#. I have my SQL Server database set up with a PostDate field set to a type of "datetime". But it's saving the date in a strange format. I added a new row through a form and I got this as the date/time string:
2012-09-28 14:56:48.910
When it gets parsed by JSON.NET it gets even stranger. I get:
2012-09-28T14:56:48.91
The date and time are obviously correct, but how do I set things so that I can parse the date into a human-friendly way? There isn't really any code to post because the date is being added when the row is inserted. I'd like to format this as "Sept. 28, 2012 2:56 pm". How do I do that? Do I need to format the string before or after it's parsed as JSON?
That's not a "strange" format at all. The second form is ISO-8601; the first is ISO-8601 without the T. Considering the strange formats you can get in JSON, it looks like you've been let off pretty lightly!
Serialization formats aren't meant to be user-friendly, particularly - they're meant to be machine-to-machine formats.
I would hope that JSON.NET would give you a DateTime after parsing; it should only be giving you the ISO-8601 format after you've converted back to JSON.
If you've got a DateTime that you want to format for user consumption, there are all kinds of options with standard and custom format strings. Don't forget that you should respect the culture of the user, as far as possible - so make sure you're taking appropriate steps to either set the thread's current culture to be the user's one, or that you're passing the culture explicitly to DateTime.ToString etc.
You can try it in C#:
.ToString("MMM d yyyy, h:mm tt")

Categories

Resources