extract date from string that contains time as well in C# - c#

I get an string from one of DTO i.e. "2020-05-17T00:00:00" and this is automapped to one of view model. Actually i only need date part i.e. 2020-05-17 and not time part from it.
Within automapper i tried directly formatting string in following way.
String.Format("{0:yyyy-MM-dd}",)
but automapper says that this can only be done within a type and not during mapping.
Also tried below way but still failed to format string.
.ForMember(src => src.FromDate, act => act.MapFrom(dest => DateTime.ParseExact(dest.FromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture)))
Not able to track where the issue is.
Any pointers or help is welcomed.

Try to get a DateTime instead of string then use the method
.ToShortDateString()
If you can't get a DateTime, convert the string to DateTime with
DateTime oDate = DateTime.Parse(iDate);
Then use the toshortdatestring

Related

Distinct and DateTime in c#

I have 2 problems. I'm trying to make my first application in xamarin, and i have list of Dates. First problem is format. When i add bind datetime to label it looks like this "25.11.2021 00:00". What i can do to have only date? second problem i have with distinct. A lot of the dates are the same and I want only one unique. I can't use DistincBy, so i write something like this MyList.Select(x => x.dateTime).Distinct().ToList() but that not work. Someone can tell me what I do wrong?
Date part
Use the .Date of DateTimes values, it will give you only the Date. Another better solution is to use the function .ToString(string format) to extract the date in a string that you will be able to use in your label. (documentation about date format)
Exemple code :
string myDate = DateTime.Now.ToString("dd.MM.yyyy");
Distinct part
For the .Select() problem, also use the .Date in your filter because it will check if dates are the same and not datetime, which contains precise data allowing to have tiny differences between 2 dates.
The code for the .Select() would be :
MyList.Select(x => x.dateTime.Date).Distinct().ToList();

Convert datetime string with this format: (yyyy-MM-dd'T'hh:mm:ss-zzz)

I am receiving a JSON string that contains a date that looks like this: 2015-07-09T08:38:49-07:00 where the last part is the timezone. Is there a standard way to convert this to a DateTimeOffset?
Here is what I have so far:
var olu = JsonConvert.DeserializeObject<OneLoginUser>(jToken.ToString(), new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd'T'HH:mm:sszzz" });
This doesn't deserialize any of the dates. I've tried using -Z and hh:mm for the timezone data, but I can't seem to deserialize any of the dates.
For reference, this is from OneLogin, a SSO provider. Here's a link to the user documentation. Notice the bit about the dates at the top.
That is a standard ISO 8601 extended format timestamp with offset, also covered by RFC 3339. There's nothing special about it.
DateTimeOffset.Parse("2015-07-09T08:38:49-07:00")
Or
DateTimeOffset.ParseExact("2015-07-09T08:38:49-07:00", "yyyy-MM-dd'T'HH:mm:sszzz",
CultureInfo.InvariantCulture)
With JSON.Net, the defaults should work well. No need to specify anything special.
JsonConvert.DeserializeObject<DateTimeOffset>("\"2015-07-09T08:38:49-07:00\"")
The fiddle Brian posted in the question comments shows that it works when deserializing a larger object. If you're still not getting it to work, perhaps you could edit your question to show the specific JSON you're trying to deserialize and the object structure you're putting it into.
One thing I noticed about your code, you show the json coming from jToken.ToString(), so somewhere you must have previously parsed using JObject.Parse. It's a little strange to do that, just to convert back to json and deserialize. Either go directly from the json string to the entity using JsonConvert.DeserializeObject, or use jToken.ToObject<OneLoginUser>() if you're already starting with jToken for some other reason. No need to mix both APIs, and it's possible you're loosing the date/time information in the process depending on what your settings are.
Try a format string like this:
"yyyy-MM-dd'T'hh:mm:ss%K"
As you can see from the example, this parses better than what you specified (the duplicate hh:mm is probably screwing things up).
string input = "2015-07-09T08:38:49-07:00";
DateTime dt = DateTime.ParseExact(input, "yyyy-MM-dd'T'hh:mm:ss%K", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(input);
Console.WriteLine(dt.ToString());

Date type in MySql

I'm new to MySQL and C#.
I stored certain values in a column with data type Date. I did not want the time, only the date to be stored.
On viewing these values using phpMyAdmin or MySql command line, I see them in the format:
YYYY-MM-DD
However, when I retrieve these values in to my web application, they are displayed in the following format:
YYYY-MM-DD HH:MM (the time is specifically 12:00).
Why does this happen? And how can I prevent this from happening?
when you store in C# your date field, you use DateTime object. In this object when you don't specify the time part will be put a default value depends on Globalization.
You can study how DateTime works here
You can convert the date to the format you like when you fetch the data, using date_format():
select date_format(datecol, '%Y-%m-%d')
This returns the value as a string.
You shouldn't retrieve the value as a string from mysql. Why? Because if you ever need to do any operations on that value, such as adding a day, then you will need to parse it back into a DateTime again. String parsing can be slow, and when it comes to dates they are prone to errors like misinterpretation of mm/dd/yyyy and dd/mm/yyyy formatting.
The problem you have is that .NET does not have just a Date type. It only has a DateTime type. So loading a MySQL DATE type, is going to get a DateTime with the time portion set to midnight.
There's no direct problem with that, except on how are outputting the result. If you just call .ToString() without any parameters, or you implicitly use it as a string, then you are going to get a result with the full date and time. You simply need to provide a parameter to indicate what formatting you want.
Without any parameters, you are getting the General "G" format. This is explained in the documentation here.
In other words:
yourDateTime.ToString() == yourDateTime.ToString("G")
You can read about all of the other formats available, here and here.
In particular, if you just want the date, then you probably want to do this:
yourDateTime.ToString("d")
Based on your comments, you should be doing this instead:
MySQL Query:
SELECT Gbstartdate FROM TblGbDef
C#:
DateTime gb_start_date = (DateTime) datareader[0];

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

Convert DateTime to string with format YYYYMMDD

I have birth dates stored as datetime in SQL Server 2008 like so:
2010-04-25 00:00:00.000
What is the best way, using C#, to convert and format this into a string with a YYYYMMDD format?
In the end, all I need is a string like:
20100425
Any help is greatly appreciated!
date.ToString("yyyyMMdd");
Should be what you need.
You need to get that value into a DateTime object and then you can use it's ToString() function like so:
.ToString("yyyyMMdd");
Are you able to get the data out of the database as a DateTime (.NET) object? If so, you can use the DateTime's instancename.ToString("yyyyMMdd")
If you haven't gotten to that stage yet, there's quite a few different ways to get the data out. It's a whole Google search in itself...
You just format the date using a custom format string:
string formatted = theDate.ToString("yyyyMMdd");
Note that the date doens't have a format at all when it's stored as a datetime in the database. It's just a point in time, it doesn't have a specific text representation until it's specifically created from the date.
Use the .ToString() method on the date time object, and pass in the format you want.

Categories