Convert String to DateTime with Leading Zero C# - 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");

Related

C# Parsing DateTime Unable to Convert String to DateTime

I followed the string output of my date variable, and parsed according to the format, but still encountered an Format Exception.
May I know what should I change?
string DOB = retrieved.Entities[i].GetAttributeValue<AliasedValue>("Contact.birthdate").Value.ToString();
//output: 4/13/2018 12:00:00AM
DateTime DOB_formatted = DateTime.ParseExact(DOB, "MM/dd/yyyy", null);
//System.FormatException
Resolution: Convert Object to DateTime
DateTime DOB_formatted = Convert.ToDateTime(retrieved.Entities[i].GetAttributeValue<AliasedValue>("Contact.birthdate").Value);
ParseExact() requires a perfect match. The MM/dd/yyyy format string would require 04/13/2018, but the value is 4/13/2018 12:00:00AM. You want M/d/yyyy hh:mm:sstt, and you should confirm day values don't have leading zeroes. There's also an overload that takes an array of format strings, if you can't trust the data source to be consistent.
Finally, per the comments, the compile-time type of Value is Object. But what about run-time? There's still a good chance the run-time type is already a DateTime value, and all you need to do is cast it. Because of internationalization/culture issues, converting to string and then re-parsing back to DateTime is suprisingly expensive. Avoiding those conversions will save the computer a ton of work, and really help performance.

How to convert 6/2/2000 to 06/02/2000 in 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

Dates of DateTime type not getting matched

I am comparing two variables of DateTime type, say d1 and d2, which are seemingly equal but the compare function returns 1 instead of 0. The value as printed for both of them is 12/10/2015 9:44:52 AM
d1 is lastModified, DateTime property of a file which is saved as a string s1 in a file.
String s1 = d1.ToUniversalTime().ToString();
When this file is later read for the string as
DateTime d2 = DateTime.Parse(s1) ;
The comparison between the two dates is weirdly not zero as expected, since they are equal, using the following
DateTime.Compare(d1.ToUniversalTime(),d2)
If I string compare both d1 and d2 after converting them to strings, they are equal and both print the above mentioned value.
I have been struggling to find out why when the date saved as string to a file and read again to be changed into date do not match.
I think I found it. Let's look at line by line.
String s1 = d1.ToUniversalTime().ToString();
With that line, you are generating 12/10/2015 9:44:52 AM as string representation of your d1.ToUniversalTime() without any milliseconds part.
DateTime d2 = DateTime.Parse(s1) ;
With that line, you are parsing this string to DateTime 12/10/2015 9:44:52 as a value but it's millisecond part will be zero.
That's why your d1.ToUniversalTime() will always bigger than dt2 and it is too normal to return a value bigger than zero from DateTime.Compare method.
If I string compare both d1 and d2 after converting them to strings,
they are equal and both print the above mentioned value.
I assume you use ToString() method to generate their string representations, this method uses The "G" standard format specifier for parameterless overload and this specifier does not represent milliseconds part for any culture as far as I know.
If you use some f, ff, fff... date and time specifiers in your ToString() method, I'm quite sure you see different results as their representations.
You have to use the round trip format specifier "o" to convert to your persistable string, else you loose the milliseconds.
String s1 = d1.ToUniversalTime().ToString("o");
Also, just to be safe, I would use the InvariantCulture to parse it (probably not necessary if your thread culture is always english).
DateTime d2 = DateTime.Parse(s1, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Fiddle
-- EDIT-- Use DateTimeStyles.RoundtripKind for parsing as recommended on MSDN.

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.

C# DateTime to be copied without format getting changed

I have a date and time which should be copied to DateTime object without changing its format.
Is there a way to resolve it?
Pls see the code below
string dateTime = "07/20/11 14:40:28";
DateTime copyDateTime = Convert.ToDateTime(dateTime);
string dateTime2 = copyDateTime.ToString();
Output:
{7/20/2011 2:40:28 PM}
If you notice the output, it got changed to PM. I want it as it is. How to get it?
EDIT:
I want dateTime2 to have the value exactly as it was for dateTime.
Format is not intrinsically associated with the DateTime. Format is simply a display property.
If you need to display it in your preferred format than simply call:
Console.WriteLine(copyDateTime.ToString("G"));
See MSDN for a complete list of standard format strings.
Before outputting, you need to convert the DateTime back into a string. By default, it simply calls "ToString" which uses the default DateTime format configured for the current user/locale.
Use ToString and specify a format to convert the datetime back into a String, then you can control the format.

Categories

Resources