How to convert 6/2/2000 to 06/02/2000 in C# - c#

I have a string coming from one place:
"06/02/2000"
I have another string coming from a different place:
"6/2/2000"
I need to compare these two to do some processing.
When comparing these two, it's different when it shouldn't be.
How can I change the second from "6/2/2000" to "06/02/2000"? this is currently a string.
I tried to do this:
DateTime dt = DateTime.ParseExact(data[i].contract_dt, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
But it's bombing because of "6/2/2000"

Parse both dates using M/d/yyyy format and then compare the actual DateTime object.
The format M/d/yyyy will work for single and double digits day/month, so it will work for both date strings.
See: Custom Date and Time Format Strings

Related

Convert String to DateTime with Leading Zero C#

I have a datetime in the format MM/dd/yyyy:
string datetime = "05/16/2018"
Now, as per the requirement, I need to convert this string to DateTime. Whenever I do so It removes leading zero.
DateTime dt = DateTime.Parse(datetime, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)
Here, It gives output as 5/16/2018 but I need it as 05/16/2018. So, how do I achieve this result?
You need to understand that a DateTime is just an object that represents a point in time. It does not store information about how it is formatted. The following are the same DateTime, just in different formats:
05/16/2018
5/16/2018
because they represent the same point in time.
It's like how int behaves. It will "remove your leading zeros" as well:
int a = 05;
Console.WriteLine(a); // just prints "5".
Because 05 and 5 are the same int, as far as int is concerned.
Whether leading zeroes are added in a DateTime depends on how you format it. They only appear when you convert your DateTime to a string. 05/16/2018 and 5/16/2018 are different strings.
If you want the leading zeroes, just specify a date format like dd/MM/yyyy whenever you want to output it:
Console.WriteLine(dateTime.toString("dd/MM/yyyy")); // prints leading zeroes!
First of all your string DateTime format(MM/dd/yyyy) is confusing! It will give misleading value for a string DataTime value like "05/08/2018". So you have to use ParseExact instead of Parse as follows:
DateTime dt = DateTime.ParseExact(datetime,"MM/dd/yyyy", CultureInfo.InvariantCulture);
It gives output as 5/16/2018 but I need it as 05/16/2018. So, how do I achieve this result?
You can simply achieve this my changing you machine DateTime format to a leading zero DataTime format! bacause by default C# DateTime takes the format of the machine Datatime format.
Well, I have also checked with a Test Console Application to confirm that your converted DateTime can contain leading zero without converting it to string if your machine DateTime format contains leading zero.
"5/16/2018" is string presentation od DateTime value.
If you want to output it with leading zero, you can use custom format:
dt.ToString("dd/MM/yyyy");

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.

Convert date in string to DateTime with same format

I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

DateTime problem when day <= 12

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
}

How to convert a string to a specific DateTime format in c#?

How to convert the string "28/09/2009" to DateTime in a specific format?
Ex:
I want to convert "2009-09-28 17:30:40" to DateTime.
I want to convert "28/09/2009 17:30:40" to DateTime.
I want to convert "20090928 17:30:40" to DateTime.
There are multiple possible formats. I tried this:
string[] formats = new string[] {"yyyymmdd","yyyymmddThhmmss","yyyy/mm/dd hh:mm:ss","yyyy/mm/dd","yyyy-mm-dd hh:mm:ss","yyyy-mm-dd"};
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime formattedDate = DateTime.ParseExact(aDate, formats, culture, DateTimeStyles.None);
This example throws an exception with the message "String was not recognized as a valid DateTime".
What's wrong in the code above?
None of your formats put the day first, like this: "dd/MM/yyyy".
Also note the capital 'M', since lower case 'm' is for 'minutes'. You have a similar problem with your hours; since your samples all use 24 hour time you need a capital 'H'.
Your format string array should look like this:
string[] formats = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss"};
Those formats exactly match your supplied sample strings.
Additionally, you probably want to use the invariant culture rather than en-US in this case. Otherwise, the '/' character in your format strings is really a culture-specific date separator, which a user might over-ride on their local system.
Finally, since you're obviously having trouble matching up the strings up, you might want to use TryParseExact(), which works just like parse exact but uses an out parameter rather than returning the value, so that it can return a boolean to indicate success or failure rather than throwing an exception.
See the complete format string reference here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Categories

Resources