I have a dateTime string as follows "\"2017-09-20T02:55:15.000Z\"". I want to parse it in C#.
DateTime gpsddt
string date = "\"2017-09-20T02:55:15.000Z\"";
var result = DateTime.TryParse(date, out gpsddt);
result is false. I don't know how to parse the above string. I got this string from a gpsd daemon. I can't find any format specifier that matches this datetime string here
The string is currently "2017-09-20T02:55:15.000Z", but it needs to be 2017-09-20T02:55:15.000Z to parse correctly. As #Chetan suggested in the comment, you need to strip out the " characters.
Add this line before parsing.
date = date.Replace("\"", "");
Alternatively, the DateTime.TryParseExact allows you to specify the source format. However it does require you to consider a lot more factors such as culture and style to use as well.
result = DateTime.TryParseExact(date, "\"\\\"\"yyyy-MM-ddTHH:mm:ss.fffZ\"\\\"\"", new CultureInfo("en-AU"), DateTimeStyles.AssumeUniversal, out gpsddt);
It is just a simple matter of doing this:
DateTime gpsddt;
string date = "\"2017-09-20T02:55:15.000Z\"";
var result = DateTime.TryParse(date.Trim('"'), out gpsddt);
Related
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 have a string representing a date in a certain format, that I wish to format differently. Someone told me to use DateTime.(Try)ParseExact, so I did:
var dateString = "2016-02-26";
var formatString = "dd/MM/yyyy";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
You see, I want to format the date as dd/MM/yyyy, so 26/02/2016. However, this code throws a FormatException:
String was not recognized as a valid DateTime.
How can I format a DateTime differently?
First of all, DateTimes have no format. A DateTime holds a moment in time and a flag indicating whether that moment is Local, Utc or Unspecified.
The only moment a DateTime gets formatted, is when you output its value as a string.
The format string you provide to (Try)ParseExact is the format that the date(time) string to parse is in. See MSDN: Custom Date and Time Format Strings to learn how you can write your own format string.
So the code you're looking for to parse that string is this, and again, make sure the format string matches the format of the input date string exactly:
var dateString = "2016-02-26";
var formatString = "yyyy-MM-dd";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
Now parsedDate holds a DateTime value that you can output in your desired format (and note that you'll have to escape the /, as it'll be interpreted as "the date separator character for the current culture", as explained in above MSDN link):
var formattedDate = parsedDate.ToString("dd\\/MM\\/yyyy");
This will format the date in the desired format:
26/02/2016
You can use this for String date
DateTime.ParseExact(dateString, format, provider);
and for provider value
CultureInfo provider = CultureInfo.InvariantCulture;
as mentioned in Microsoft documentation
i have a string like "14-Nov-2014" , i want to convert this string to this 14.11.2014 format.
after converting i want to add 14 days to above date.
given date is not Datetime format.
Old date="14-Nov-2014"
new date=14.11.2014
is there any way to do in c#?
Assuming,
var myString = "14-Nov-2014";
First parse the string, most likely using DateTime.ParseExact. Assuming a few things about the format you have, you could do the following. Note you most likely should specify the proper culture for the third argument:
var dateTime = DateTime.ParseExact(myString, "dd-MMM-yyyy", null);
Then you can add 14 days to it easily:
var dateTime = dateTime.AddDays(14);
To get a new string in a different format just use ToString with a format string. For example:
var myNewString = dateTime.ToString("d.MM.yyyy");
I am having a problem while converting
2003-11-05T16:35:30Z to "11/5/2013"
I tried below
DateTime.ParseExact("2003-11-05T16:35:30Z", "dd/MM/yyyy", null)
but I am not getting the value I expect.
You want to do this:
DateTimeOffset.Parse("2003-11-05T16:35:30Z").ToString("dd/MM/yyyy")
What you're doing is parsing the data as if it were in the format dd/MM/yyyy - instead, you want to parse it as the universal format it is, and then convert it to a string with your format string.
DateTime.Parse will take a string and return a date time. To get a string back out, you simply use the ToString method.
Try This:
string myDate = DateTime.ParseExact("2003-11-05T16:35:30Z",
"yyyy-MM-ddTHH:mm:ssZ",null).ToString("M/d/yyyy");
When parsing you specify the format that you are parsing from, then you format the DateTime value using the new format:
string reformatted =
DateTime.ParseExact("2003-11-05T16:35:30Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", null)
.ToString("dd/MM/yyyy");