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);
Related
I've encountered a problem in which I am looking for a good solution.
Consider I have a node that passes data with corresponding date with the format of yyyy-MM-dd
For example: OK 2020-08-23 (Time is omitted)
And in the destination node I do parse Date by simple code
Convert.ToDateTime(date)
Recently I we noticed that destination node not properly handles date and looks it has Ambiguity in parsing date correctly
For example : if I pass data Like OK 2020-08-23 it works correct as because it knows that number of months never exceeds from 12 so 23 is day and 08 is month. However, when data is OK 2020-02-03 it don't know 02 is month or 03?
How can I resolve this Ambiguity in a proper manner?
Try using the ParseExact method and specify a custom format you need to parse:
DateTime.ParseExact(theDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
More information here.
The method has an overload where you can pass a format provider
var dtFormat = new CultureInfo("en-US", false).DateTimeFormat;
string result = Convert.ToDateTime("12/01/2011", dtFormat);
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.
I want to convert my JSON formatted date to C# DateTime variable. Trying to convert it with Convert.ToDateTime
("2016-01-15T11:44:52-07:00")
is giving me this output
"1/16/2016 12:14:52 AM"
I am not able to find out whether it is a correct output or not because my input date is 15 Jan 2016 but in output it is 16 Jan 2016.
How can I convert a JSON date value to a C# date value?
Looks like your current timezone is UTC +05:30 right now and that's why Convert.ToDateTime method adds those value to the result and generates 1/16/2016 00:14:52 as a value.
Since your string has an offset part, I would parse it to DateTimeOffset instead of Datetime.
var dto = DateTimeOffset.Parse("2016-01-15T11:44:52-07:00");
This will generate {15.01.2016 11:44:52 -07:00} as a DateTimeOffset.
But since you said this is related with Json, this technology should have some methods to parse it as well. It would be better to use those methods but I'm not familiar with JSON.
You seem to have problems with the time zones. Try parsing with DateTimeStyles.RoundtripKind
using System.Globalization;
var s1 = "2016-01-15T11:44:52-07:00";
var date = DateTime.Parse(s1, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
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
}
ive got 2 strings, date:"27.03.11 " and time:"15:04", which id like to format as a PubDate elemnt for a rss file like Fri, 18 Nov 2005 19:12:30 GMT.
How can i do this in c sharp?
Use the following steps:
Parse the date and time strings into one DateTime variable. Use the DateTime.ParseExact static method for this.
Convert the datetime to GMT using the methods of the TimeZone class (if desired---I don't think this is mandatory according to the RSS specification).
Format this variable into a string using the DateTime.ToString method. The following MSDN pages will help you choose the correct format string based on your needs:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Since RSS requires dates to be in the RFC 822 format, the following related SO question might help you with the last step:
How do I parse and convert DateTime’s to the RFC 822 date-time format?
EDIT: For the first step, have a look at this example:
var s = "27.03.11 15:04";
var dtm = DateTime.ParseExact(s, #"dd.MM.yy HH\:mm", null);
(The \: ensures that : is seen as a literal : rather than a culture-specific time separator.)