How do you set the DateTime format string in Newtonsoft? - c#

I'm trying to get Newtonsoft to convert a string to a DateTime. This is the string:
13/02/2019 05:13
I try to tell Newtonsoft how to do this by using one of these:
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy HH:mm" };
var converters = new List<JsonConverter>() { dateTimeConverter };
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = converters
};
or
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
DateFormatString = "dd'/'MM'/'yyyy' 'HH':'mm"
};
and of course it will just go right ahead and tell me that's fine and then blow up as it tries to process the second day of the thirteenth month.
I need this to work globally. How do I get Newtonsoft to do this?

This was in WebAPI and the problem was I wasn't setting the same Json.Net that WebAPI was using.
I fixed it by putting this in Application_Start of global.asax.cs:
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy HH:mm" };
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(dateTimeConverter);

you can convert a string to a datetime like this :
string iString = "2005-05-05 22:12 PM";
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
MessageBox.Show(oDate.ToString());
i hope to help you.. :/

Related

Get TimeSpan from HH:mm:ss string

I'm trying to get a TimeSpan from "24:30:00" string so I can define cacheOptions in C# but I'm getting 24 days instead of 24 hours.
string cacheExpirationTime = "24:00:00";
var cacheOptions = new MemoryCacheOptions()
{
ExpirationScanFrequency = TimeSpan.Parse(cacheExpirationTime, CultureInfo.InvariantCulture)
};
I also tried without using CultureInfo, but it didn't work.
Which is the proper way to do this?
24 hours is 1 day, so you should format it as such.
string cacheExpirationTime = "1.00:00:00";
var cacheOptions = new MemoryCacheOptions()
{
ExpirationScanFrequency = TimeSpan.Parse(cacheExpirationTime, CultureInfo.InvariantCulture)
};
If you want to use the format hh:mm:ss. You need to specify the format, here "hh:mm:ss" is used. hh is for hours, mm for minutes, and ss for seconds.
Be aware that 24:00:00 could not be used because it's not a valid value for a TimeSpan object. The largest possible value for a TimeSpan object is 23:59:59, so any value greater than that will cause an OverflowException to be thrown.
string cacheExpirationTime = "23:59:59";
string format = "hh\\:mm\\:ss";
var cacheOptions = new MemoryCacheOptions()
{
ExpirationScanFrequency = TimeSpan.ParseExact(cacheExpirationTime, format, CultureInfo.InvariantCulture)
};
By default, TimeStamp assumes the input string represents a time duration in the format days.hours:minutes:seconds so you need to use a custom format string with TimeSpan.ParseExact() method like this:
string cacheExpirationTime = "24:00:00";
var cacheOptions = new MemoryCacheOptions()
{
ExpirationScanFrequency = TimeSpan.ParseExact(cacheExpirationTime, #"h\:mm\:ss", CultureInfo.InvariantCulture)
};

Cannot deserialize JSON with both UTC and non UTC formatted datetimes

I am reading in JSON from an external API. The datetime values are formatted differently for some reason and I cant get it to automatically deserialize into my object using Newtonsoft.Json.
For example, suppose the following is my JSON (the only diff in the two datetime values is the first one ends in 'Z' and the second does not):
string json = "{ \"DateTime1\" : \"20131101T000000Z\", \"DateTime2\" : \"20131101T000000\" }";
Then I need to parse the 2 datetime fields into an object containing DateTime1 and DateTime2 properties like this:
class Foo
{
public DateTime DateTime1 { get; set; }
public DateTime DateTime2 { get; set; }
}
My deserialization code looks like this:
var format = "yyyyMMddThhmmssZ"; // your datetime format
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format };
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
serializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
serializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
string json = "{ \"DateTime1\" : \"20131101T000000Z\", \"DateTime2\" : \"20131101T000000\" }";
try
{
var serializer = JsonSerializer.Create(serializerSettings);
var o3 = JsonConvert.DeserializeObject<Foo>(json, dateTimeConverter);
}
catch(Exception ex)
{
var x = ex.Message.ToString();
}
return;
Running the code above gives me:
String was not recognized as a valid DateTime
Any help would be greatly appreciated!
Your datetime format string for IsoDateTimeConverter doesn't look correct, try to update it per following
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyyMMddTHHmmssK" };
According to Custom date and time format strings,
K format specifier is used for time zone information, there is no Z format specifier

How to correctly deserialize a Json DateTimeOffset?

i got a problem while i try to deserialize a DateTimeOffset from a json. I saw a lot of questions here, but no one seems to work. I got from Json this dateTime : 05/04/2019 02:39:33 PM GMT and i want to keep the offset to zero. After the deserialization, by the way, i got my object with same exact time(In this case 02:39:33 PM) but with my time zone ( +02:00). I tried these two workaround, without success:
First of all, i tried to setup setting to my deserializer:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DateParseHandling = DateParseHandling.DateTimeOffset,
DateFormatString = "dd/MM/yyyy hh:mm:ss tt 'GMT'"
};
I tried this converter too:
class DateFormatConverter : IsoDateTimeConverter
{
public DateFormatConverter(string format)
{
DateTimeFormat = format;
DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal;
}
So, i expected this reseult:
05/04/2019 02:39:33 PM +00:00
thanks to all that will answer me!
Maybe change DateParseHandling.DateTimeOffset to DateParseHandling.None?
I managed to got the expected result by change DateParseHandling = DateParseHandling.None in the Setting of serializer.

Convert String (2015-FEB-17) to Date (20150217) format

I tried the following but couldn't get it
string s= "2015-FEB-17";
//I want it to be converted to date format as
date = "20150217"
//I tried doing as follows but didn't work
var myDate = DateTime.ParseExact(dt, "yyyy-MMM-dd", CultureInfo.InvariantCulture);
why not shorten it since you are using the .ToString("yyyyMMdd") you are dropping the time portion of the new value
string sDateStr = "2015-FEB-17";
var newDateFrmt = Convert.ToDateTime(sDateStr).ToString("yyyyMMdd");
20150217 becomes the expected answer based on the format..
not to be redundant this approach can also be taken
string sDateStr = "2015-FEB-17";
var someDate = DateTime.ParseExact(sDateStr, "yyyy-MMM-dd", CultureInfo.InvariantCulture);
var newDateFrmt = someDate.ToString("yyyyMMdd");
ParseExact turns the string into a DateTime. You then need to format the DateTime as a string.
string s= "2015-FEB-17";
DateTime myDate = DateTime.ParseExact(s, "yyyy-MMM-dd", CultureInfo.InvariantCulture);
string result = myDate.ToString("yyyyMMdd"); // now it's "20150217"
Also, you were missing dashes in the ParseExact format string.
If your application only handles US-style dates with no internationalization, it's best to specify CultureInfo.InvariantCulture.
Try
var myDate = DateTime.ParseExact(s, "yyyy-MMM-dd", CultureInfo.InvariantCulture);
var q = myDate.ToString("yyyyMMdd");
or just
var q = DateTime.ParseExact(s, "yyyy-MMM-dd", CultureInfo.InvariantCulture)
.ToString("yyyyMMdd");

String date time format

I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..

Categories

Resources