Retrieve format of date from date value - c#

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

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

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.

Can't convert DateTime format from MM/dd/yyyy to yyyy-MM-dd

I know this is a recurrent question but I cannot seem to be able to get this to work even after a lot of research! I want to convert a string to a DateTime.
public DateTime ConvertToDateTime(string thisDate)
{
return DateTime.ParseExact(thisDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
(EDITED)
I give "2012-03-07" as a parameter and I get a DateTime that is 03/07/2012 12:00AM. When I wanted it to return: 2012-03-07 00:00:00
Your code is correct; your expectations are wrong.
When a method returns a DateTime, it has no format. Well, more accurately, it has a binary in-memory format that has no relation to its string format.
The debugger formats the DateTime to show it to you, but that has no bearing on the DateTime value itself. The format it uses is presumably determined by your locale settings.
When you want to display the DateTime to a user, or pass it as a string to some other function, you can format it as you like using one of the ToString overloads.
It may be that you are displaying or passing the return value of the function you've given; if so, the error is in the code displaying or passing the DateTime, not in the function you've given. If that's the case, edit your answer to include that code, and perhaps we can help you fix it.
Try this
public String ConvertToDateTime(string thisDate)
{
return DateTime.ParseExact(thisDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture).toString("yyyy-MM-dd");
}

.NET DateTime to BizTalk DateTime

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . BizTalk expects same datetime format how can i pass it as Datetime in that format ? No string . Date time with same format as source date.
You should be able to do something like this to get it into a DateTimeOffset object. After that you can call whatever methods you want on it.
DateTimeOffset dateTime = DateTimeOffset.Parse( "1999-05-31T13:20:00.000-05:00" );
To get the value back just use a formatting string.
dateTime.ToString( "O" ); //this should be the same format as you started with
Here are some other options http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Here is a link to the DateTimeOffset structure
http://msdn.microsoft.com/en-us/library/bb351654.aspx
I hope this helps.
The DateTime object is format-independent (for the most part). So whether or not it starts in the format you list or not doesn't matter. You can always get it back into that format (using the ToString("o") function). But that's as a string (when format matters).
After a quick search, it looks like you must be talking about string format, even though you said no string. So the other answer or the ToString("o"); part of mine is relevant.

Categories

Resources