date time format issues in C# - c#

I am attmepting to change a date time format for a search from ddd MMM dd HH:mm:ss zzz yyyy to just simply yyyy-MM-dd i'm not able to get the syntax right in my conversion so any help would be great.
public DateTime CreatedAt
{
get
{
return DateTime.ParseExact(this.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
}
}
public DateTime SearchDate
{
get
{
return DateTime.ParseExact(CreatedAt.ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
}
searchDate is my issue.

This won't work:
return DateTime.ParseExact(CreatedAt.ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
because CreatedAt.ToString() is going to create a date time string in the default format (not yyyy-MM-dd, which is how you're trying to read it).
But more importantly, why are you trying to convert a date from one string format time to another? If you have the DateTime value (CreatedAt, in this case), you can render it however you want (e.g. CreatedAt.ToString("yyyy-MM-dd")) There just doesn't seem to be any sense in converting it to a string and parsing parts of it.
And as Bob pointed out, if all you want is the date portion, take CreatedAt.Date. Try to think about what your real goal is, though and try to take the shortest route with the fewest conversions (and therefore conversion problems) as possible.

Related

Save Date format of "December 02, 2015 07:25:11 PM" in DateTime variable

I have a variable
private DateTime? createdDate = null;
This consists of the date in 12/2/2015 7:14:37 PM format. I need to modify the date format to December 02, 2015 07:25:11 PM and then assign this new format to the same createdDate variable. I was able to modify it using
DateTime date;
if (DateTime.TryParse(createdDate, out date))
{
string modifyDate = date.ToString("MMMM dd, yyyy hh:mm:ss tt", CultureInfo.CurrentCulture);
}
But when I tried to assign it back to createdDate it cannot save since type is string, and to avoid this I tried Convert.ToDateTime but this takes it back to "12/2/2015 7:14:37 PM" format. Does anyone know how can I save "December 02, 2015 07:25:11 PM" in createdDate variable. Thanks.
DateTime does not have a format - it's just a point in time. The format is relevant when you display the value. That's where you need to specify what format you want.
That also means you can just use createdDate - there's no need to create a new date variable to represent the same date in a different format.
As D Stanley said, its just a value of time. how that value needs to be displayed is controlled by formatting so formatting is just the presentation.
May be you can write a property like this to make things easy for you.
The consumer of this property will get the impression they are saving a formatted date & when they fetch it, they'll get a formatted output.
private DateTime timePoint;
public string FormatedDateTime
{
get
{
return timePoint.ToString("MMMM dd, yyyy hh:mm:ss tt", CultureInfo.CurrentCulture);
}
set
{
timePoint = Convert.ToDateTime(value);
}
}
Write me a comment in case of any issues

Converting a String into a Valid DateTime Format

I have two Timestamps that are saved to and read from two XML files.
Currently I am reading the timestamps from the xml files in a WCF Service method, so they are coming in as Strings , but I need them to be converted into DateTime so they can be compared.
The obvious Convert.ToDateTime(TimeStampString) renders this error at Runtime -
String was not recognized as a valid DateTime
As does
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
Both Timestamps are in the correct format for DateTime (mm/dd/yyyy hh:MM:ss).
I've even tried splitting the timstamp strings into String[] and assembling my own DateTime object by hand, and I still received the error.
Is this a format issue? How can I make my String a valid DateTime?
It's a format issue
mm/dd/yy hh:MM:ss
should be
MM/dd/yyyy hh:mm:ss
(basically, swap the upper case MM in the date & the lowercase mm in the time)
I resolved the issue by removing any attempts to alter the format from US, so Strings came in with US format - then used an IFormatProvider to alter the format at conversion time.
IFormatProvider localFormat = new System.Globalization.CultureInfo("fr-FR", true);
DateTime ContentLastUpdatedTime = DateTime.Parse(ContentLastUpdatedStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
DateTime ContentLastGrabbedTime = DateTime.Parse(LastGrabbedTimeStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
You need to use
DateTime.ParseExact(TimeStampString, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
instead of
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
The issue is lower case mm which is used for minutes, You need MM upper case MM, plus your date is in 24 hours format, and you need upper case HH for hour part , so your format should be:
MM/dd/yyyy HH:mm:ss
(considering you have yyyy in your original code based on your comment)
See: Custom Date and Time Format Strings
Here you go
var dtedatetime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
DateTimeOffset dto;
bool bIsParsed = DateTimeOffset.TryParseExact(dtedatetime , "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dto);
var result = dto.DateTime;

ASP.NET format string date

I am connecting to a database, executing a query, and putting the data in a list. I have strings that have dates like so mm/dd/yyyy hour:minute:second AM or PM I am looking to format this data into yyyy-mm-dd with no time.
This is where I am assigning the data:
airportItems.ContractReceived_F = dataReader.GetValue(1).ToString();
how would I convert the dataReader.GetValue(1).ToString(); to the date format I want?
I have tried the following:
airportItems.ContractReceived_F = string.Format("{0:d}", dataReader.GetValue(1).ToString());
I am defining ContractReceived_F as string:
public string ContractReceived_F { get; set; }
and it still returned the time.
Use this:
airportItems.ContractReceived_F = dataReader.GetDateTime(1).ToString("yyyy-MM-dd");
where yyyy represents the year, MM represents the month and dd represents the day.
why not parse the data you need to like this
DateTime unparsed_date = mydatevalue; //any date in any date format
string parsed_date = unparsed_date.toString("dd mm yyyy");
Theres an article on the different parses on msdn that i found for you
check it out
Credit goes to fubo for the link (thumbs up)
I suggest to use the TryParseExact
Then you choose the date format that you need
For example :
DateTime OutputDate = null;
DateTime.TryParseExact(DateFromTheView, "yyyy/MM/dd H:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
In the example : the format is "yyyy/MM/dd H:mm:ss tt" and the input date string is DateFromTheView. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.

how can I identify the format of a string to be used with DateTime?

I have a database script that returns date time string and my problem is that I don't know what format my string will be. The reason is that I have desktop in different culture and they could return any kind of format. My ultimate goal is, from the string to return the DateTime.
As I am trying to write something I am realizing that I would need to try any kind of format to make sure something comes back to me without an exception.
There should be a better way to do this without trial and error.
This is what I have but it only works for a few formats:
public static DateTime FromQueryResultString(string dttmString)
{
string[] formats = { "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss", "dd.MM.yy hh:mm", "M/d/yy h:mm tt", "ddd MMM dd H:mm:ss yyyy", "dd.MM.yy hh:mm", "dd.MM.yy HH:mm","ddd MMM yy H:mm:ss yyyy" };
string name = Thread.CurrentThread.CurrentCulture.Name;
IFormatProvider format = new CultureInfo(name, false);
DateTime formattedDate = DateTime.ParseExact(dttmString, formats, format, DateTimeStyles.None);
}
Try this:
DateTime parsedDate;
if(DateTime.TryParse(dttmString, parsedDate))
{
//TODO
}
I think you're missing a fundamental concept.
Considering that you're talking about a DataBase script, it' a script, I immagine, which returns a data from database. Your database has to always hold a DateTime, floating point numbers and other culture sencitive data in one common format. In this case, you will have one single stable Data Access Layer which will recover and manipulates data recovered from Rome, Paris, Beijing or Abu Dhabi. The client program that data will visualize in culture dependent way.
In short: choose one format and store it in that way.
It's clear that this architecture is not always possible to have, but from my expirience it is possible in 99% of cases.
Hope this helps.
You can get the current culture set up via the CultureInfo.CurrentCulture property. Then you can get the date time format from the CultureInfo return object's Property DateTimeFormat. This means that Windows handles it and you do not have to do any special manual handling.
EDIT: Sample Code
public static DateTime FromQueryResultString(string dttmString)
{
string[] formats = { "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss"
IFormatProvider format = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
DateTime formattedDate = DateTime.ParseExact(dttmString, formats, format, System.Globalization.DateTimeStyles.None);
}

How to do Convert.ToDateTime or parse date in C# but only get dd/mm/yyyy in C# 2.0?

As topic says, I have a string like
string CreatedDate = "12/09/2010"
and I want to pass it to a web method that only accepts it as DateTime
customer.dateCreated = Convert.ToDateTime(CreatedDate);
naturally it add hh:mm:ss after the date which the web service doesn't accept so how can I keep the date in the short format when I convert it to a date?
Thanks in advance
A DateTime value doesn't know anything its formatting (and indeed it shouldn't). It sounds like your web service is broken if it's not accepting standard date/time formatting. What's the implementation of the web service? Is "customer" an autogenerated proxy class?
Assuming you have:
void WebMethod(DateTime date);
and
string dateString = "12/09/2010";
then do next:
DateTime date;
if (DateTime.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
WebMethod(date);
}
else
{
// raise an error - specified date is not in specified format
}
Note:
date.Hour // 0
date.Minute // 0
date.Seconds // 0
Otherwise, if you have DateTime object and WebMethod(string date) where date should be in specified format, then:
DateTime date = ..;
WebMethod(date.ToString("dd/MM/yyyy"));
DateTime has a .Date property that strips the time information.
Does the WebService accept the date as only "12/09/2010"? Typically a webservice should follow the reccomendations here
XML Schema Part 2: Datatypes Second Edition
Which is UTC format. Using:
DateTime.ParseExact(value, "ddd MMM dd HH:mm:ss zz00 yyyy", null);
solves the problem most times.

Categories