C# Parsing DateTime Unable to Convert String to DateTime - c#

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.

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");

How to make datetime.now return date in UK format with c#

I want datetime.now to return the datetime object in UK format. It does so on my local computer but when I upload the code to the server it does it in US format
DateTime doesn't have any format associated with it. Formatting is just for presentation. You can do:
string formattedDate = DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
Or supply a specific/custom format like:
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
I want datetime.now to return the datetime object in UK format.
There's no such concept, any more than an int is a value "in hex" or "in decimal". A DateTime is just a DateTime - you can specify the format when you convert it to a string. It's really important to understand the difference between an inherent value, and what it looks like after it's converted to text - very few types are aware of a custom, modifiable format to use when converting themselves - it's either provided externally (as for DateTime, numbers etc) or simply fixed.
Before you convert start hard-coding a UK format though, I would strongly advise you to consider exactly what you're doing:
Ideally, avoid the conversion in the first place. A lot of the time, string conversions are unnecessary and can be problematic.
Is the text going to be consumed by another machine? Use an ISO-8601 standard format.
Is the text going to be consumed by a person? Use their culture rather than some arbitrary one you decide on.
... Or display it in a dedicated control...
You can use the overload of the ToString method: ToString("dd/MM/yyyy"), or: ToString("yy/MMM/dd"), etc. etc.
Read more about it here: https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
Also sounds to me that you might want to configure your (UI-)Culture in the web.config? Then it will always be in the same format regardless of the culture of your US/Japanese/european server culture..
More about that here: https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
LogDate = DateTime.UtcNow.AddHours(1);

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.

Retrieve format of date from date value

I am receiving some data into a variable of type object. In certain cases this data are date values. For that data, I would like to convert this to a string and return it in the same format as it was passed. In some cases, the object could be a datetime, in others a date only or time only values.
As soon as I convert the object to a date or a string, it is obviously given a time of midnight which in my scenario may be a valid time (so I cannot test to see if the time is midnight in which case I could deduce that it would have been a date only date value, nor can I use regex on it as there will always be a time element).
Intellisense shows me it correctly, ie in the format I am wishing to return the value.
Is there an easy way to achieve this (hopefully without using reflection)
Many thx
Simon
Your question is a little unclear but I think you're looking for something like this:
DateTime result;
if (DateTime.TryParse(value, out result))
{
// use result here
}
In the above code value is a string that represents the data coming in. The code will only enter the if block if the string is a valid DateTime. At which point you can do the processing you need on it.
Im not sure i understand the question but i would recommend you to take a look at this conversion example on MSDN, and see the Documentation of the DateTime Structur it contains a lot of Conversion/Formatting Methods i hope it helps.
There are many way to do formatting on the datetime and one of the simple way is fetch the data from the required table in the desired format. Like here you need to display the date and if you your format is dd/MM/yyyy then try this
select Convert(varchar(10),StartDate,103) as StartDateformat from table where filtername=#filtername
use this link to find other format Cast and Convert
From local variable to DateTime Conversion
DateTime todateformat = Convert.ToDateTime(txttodate.Text.Trim());
From DateTime to local variable Conversion in specific format
string startdate = todateformat.ToString("dd/MM/yyyy hh:mm:ss");

Categories

Resources