I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:
//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }
//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); }
How can I apply String.Format correctly to retrieve only month and year?
A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.
In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
You can try parsing dateString to DateTime and then format.
DateTime dateTime = DateTime.Parse(dateString);
dateTime.ToString("MM/yyyy");
String.Format() uses numeric placeholders:
return String.Format("{0:MMyyyy}", DataCupom);
Where the 0 in the format string means to look at the first additional argument position for the value.
You can also use interpolation:
return $"{DataCupom:MMyyyy}";
or a simple ToString() call:
return DataCupom.ToString("MM:yyyy");
Related
I have to parse date string in C#. The dates are all ensured to start with year, month, day. But I do not know what dividers will be between the 3 parts.
Additionally the date string may also include a time part after the date.
Basically as long as the format has the year first, month second, and day third, I should parse it as a valid date regardless of which dividers are used and whether a time is included. Any other date formats should be rejected as invalid.
I can not figure out how to do this without writing a long if/else.
How do I parse a string into a C# datetime object, given the restrictions mentioned?
You can check the length of the input string is at least 10 characters, and if it is, work out what the separator should be by looking at the 5th character in the string.
Then you can use the separator to construct a format string that you pass to DateTime.TryParseExact() to parse the date. You also have to truncate the date string to 10 characters to ignore any date part at the end.
An example implementation looks like this - it returns null if the date didn't parse; otherwise, it returns the correctly parsed date:
public static DateTime? ParseDateWithUnknownDivider(string dateStr)
{
if (dateStr.Length < 10)
return null;
char divider = dateStr[4];
if (DateTime.TryParseExact(
dateStr.Substring(0, 10),
$"yyyy\\{divider}MM\\{divider}dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime result))
return result;
return null;
}
Note that this ignores the time part and will always return the time part as 00:00:00. If that's not what you meant, you will need to specify in your question what the time part would look like. For example, would it be separated from the date part by a space? And would it always be hh:mm:ss? And would it be 24hour clock?
try this code
string yourDateTimeString = ....;
string format="yyyy/MM/dd";
var dt = DateTime.ParseExact(yourDateTimeString,format,null,System.Globalization.DateTimeStyles.AssumeLocal);
I'm trying to convert an Active Directory attribute (whenCreated) into DateTime then String, but I keep getting a FormatException, any ideas why? Here is the code:
string format = "YYYYMMDDHHMMSS.0Z";
DateTime dt = DateTime.ParseExact(sResult.Properties["whenCreated"][0].ToString(),format,CultureInfo.InvariantCulture);
string whenCreated = dt.ToString();
Also, sResult.Properties["whenCreated"][0].ToString() is the result from an Active Directory search (the date retrieved) and has the String (Generalized Time) syntax.
The DateTime.ParseExact method expects a format string, that tells it where in the input string is which component of a valid date. Your format of 'd' does not meet this criteria. I don't know the content of your input (would help if you add it). But lets assume it would be "2017/31/05 10:27:45" for today. Your format string would then have to be: "yyyy/dd/MM HH:mm:ss"
DateTime dt = DateTime.ParseExact("2017/31/05 10:27:45","yyyy/dd/MM HH:mm:ss",CultureInfo.InvariantCulture);
According to the documentation linked by the OP:
The format for the Generalized-Time syntax is "YYYYMMDDHHMMSS.0Z". An example of an acceptable value is "20010928060000.0Z"
And:
If the time is specified in a time zone other than GMT, the differential between the time zone and GMT is appended to the string instead of "Z" in the form "YYYYMMDDHHMMSS.0[+/-]HHMM". An example of an acceptable value is "20010928060000.0+0200"
So you'd need two format strings in order to parse the strings, like this:
string adDate = "20010928060000.0Z";
string adDate2 = "20010928060000.0+0200";
string format = "yyyyMMddhhmmss.0Z";
string format2 = "yyyyMMddhhmmss.0zzz";
DateTime dtdtdt = DateTime.ParseExact(adDate2, new string[] { format, format2 },
CultureInfo.InvariantCulture,DateTimeStyles.None);
When use the .ParseExact() method for the DateTime, i always get the same output as the string i put in. Here is my code:
[Authorize(Roles = "Backoffice, Manager")]
[HttpPost]
public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
{
if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
{
DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss",
CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);
FilmShow filmShow = new FilmShow
{
Film = filmRepository.GetFilm(newFilmShow.FilmId),
Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
ThreeDimensional = newFilmShow.ThreeDimensional,
Date = dbDate,
SpecialEvent = newFilmShow.SpecialEvent
};
filmShowsRepository.AddShow(filmShow);
return View("SuccesfullFilmShowCreate");
The string dateString is formatted good, but it is a string and I need to store it in the database as a format DateTime like this "year-month-day hours:minutes:seconds". But for whatever reason the ParseExact doesn't seem to work in my case. The DateTime format i get is "dd-MM-yyyy HH:mm".
It doesn't do what you want because, well, that function isn't supposed to do what you are describing.
ParseExact simply indicates that the input must match the given format in order to be used (and not throw an exception). It is a counterpart to Parse which will accept any valid Date/Time format. It has absolutely no bearing on the future format of any string representation of the DateTime object it creates.
If you want to output it in a given format, pass your format string into ToString before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it shouldn't matter.
Example:
string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");
Reading your question more closely, I realize that you seem to think that DateTime has some "stored" format. It does not. DateTime is just a collection of numbers that hold the information required to represent a date and time. The format you are describing only exists in string representations.
I am trying to convert a string to a datetime format in C#.
DateTime SnapDate = Convert.ToDateTime(valid(odr, 4)).Date;
protected string valid(OleDbDataReader myreader, int stval)//if any columns are found null then they are replaced by zero
{
object val = myreader[stval];
if (val != DBNull.Value)
return val.ToString();
else
return Convert.ToString("");
}
And it gives me the following error: "The string was not recognized as a valid DateTime. There is a unknown word starting at index 0."
I tried several things like: parse and parseExact but still didn't get it.
I am reading this data from an excel sheet.
Looks like your input string is in en-US format. Try specifying CultureInfo object into Parse method:
DateTime SnapDate = DateTime.Parse(valid(odr, 4), new CultureInfo("en-US")).Date;
It will force Parse method to look for date in M/d/yyyy format, which is valid for your input string of 3/21/2013.
I'd say rather than using your system culture or choosing one, pick the exact date format and use that, like:
DateTime dt = DateTime.ParseExact("3/21/2013", "M\\/d\\/yyyy", null);
No ambiguity on the order of parameters, or on the date separator.
FYI: The reason I use a backslash before the forward-slash is to escape the forward-slash - forward-slash means date separator, not necessarily the forward-slash, so escaping it removes any possible ambiguity.
I have a string of the next format "ORDER20100322194007", where 20100322 is a date and 194007 is a time. How to parse a string and get the contained DateTime object?
Will it always start with ORDER?
string pattern = "'ORDER'yyyyMMddHHmmss";
DateTime dt;
if (DateTime.TryParseExact(text, pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
// dt is the parsed value
}
else
{
// Invalid string
}
If the string being invalid should throw an exception, then use DateTime.ParseExact instead of DateTime.TryParseExact
If it doesn't always begin with "ORDER" then do whatever you need to in order to get just the date and time part, and remove "'ORDER'" from the format pattern above.
You can use DateTime.ParseExact method to specify the format that should be used while parsing.
If you don't have a fixed structure of your string say order will not always be there then you can use regex to separate the numbers and characters and then use convert to datetime function for the numbers separated.