json.net deserialize datetime in object - datetime

I have a problem with deserialization of datetime. In JSON it comes in this format 2016-10-04T15:20:00 but after deserialialization it changes to the AM/PM time format and I need to preserve the 24 hour format. Is there any way how specify the format?

When you deserialize to a date, the format is not stored inside the date object. Instead, the formatting happens on output. The default format for your locale is probably using 12-hour time. If you want a different format, you can pass a format string to the ToString method:
string json = #"{ ""date"": ""2016-10-04T15:20:00"" }";
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
Console.WriteLine(foo.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Fiddle: https://dotnetfiddle.net/ibLCbG

Related

Format local time to custom time

I have a saved time that is in the format of this: moment().format('llll').
I want to convert that time to this format: YYYYMMDD?
I tried this:
let Time = moment().format('llll')
moment(Time, 'YYYYMMMDD')
That results in moment.invalid(/* 2019年7月4日星期四 16:03 */)
Anyone an idea on how to do it?
moment().format('llll') gives you a formatted string.
To create a moment object with a formatted string, you should also provide the string format.
let Time = moment().format('llll')
moment(Time, 'llll')
After that, you can easily format moment object as string
moment(Time, 'llll').format('YYYYMMMDD')

issue with datetime jquery asp.net mvc

I have an issue with date.In my Model class I have used DateTime property(I used Code First), for transferring json data from action to another action I use Jquery ($.ajax), my date convert in this format, I think it milliseconds:
/Date(1188594000000)/
I tryed to convert it using js, not working:
var date = new Date(mydate);
/Date(1188594000000)/ is a string and the long numbers inside the brackets are the milliseconds since the beginning of the unix epoch time. You cannot pass that(the string as it is) to Date constructor. If you want to generate a datetime object from that value, you should remove the first 6 characters (/Date() and pass the milliseconds only
var mydate='/Date(1188594000000)/';
var dateVal= parseInt(mydate.substr(6));
var dateObj= new Date(dateVal);
console.log(dateObj);
The statement mydate.substr(6) will return a string value like "1188594000000)/" and passing this to parseInt method returns the number 1188594000000 which can be safely passed to the Date constructor.

moment.js format date as iso 8601 without dashes?

How do I format a date as iso 8601 using moment.js but without the dashes and colons and setting the time to 0 e.g. if I have a date like this:
2016-10-08T09:00:00Z
How do I format as :
20161008T000000Z
Doing moment(date).toISOString() gives 2016-10-08T09:00:00.000Z which is not what I want.
You can simply parse your input into a moment object and use startOf to set time to 00:00:00. Then you can use format method to get a string in your custom format.
Here there is a working example using a string input, you can use the same code also if your input is a javascript Date object.
// Input date as string
var s = '2016-10-08T09:00:00Z';
// Reset time part
// var m = moment(s).startOf('day'); // no UTC
var m = moment.utc(s).startOf('day'); // UTC mode
// Format using custom format
console.log(m.format('YYYYMMDD[T]HHmmss[Z]'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Issue in converting Timespan variable to 12 hour format

I have a nullable variable Start time
Timespan? st=e.StartTime;//Null-able variable;
I am trying to get time in AM/PM format but I am unable to get it.
DateTime date = Convert.ToDateTime(st.ToString());
String f = String.Format("{0:hh:mm:tt}", date);
Error is:
System.FormatException: String was not recognized as a valid DateTime.
If you were to output the results of st.ToString(), you will find that it doesn't contain any date information, only hours, minutes and seconds.
This isn't a valid format for a DateTime, which generally contain date and time information.
You don't need to convert your TimeSpan to a DateTime to format it, you can just use TimeSpan.ToString():
string f = st.Value.ToString(#"hh\:mm\:tt");
For reference: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Also, note the \ before the :, you must do this if you want to include literal strings in the output, as mentioned at the bottom of that documentation page.
Converting a timespan to a date is not possible, a timespan represents x amount of minutes/hours/whatever and you cannot get an exact date from that alone. If you have a date as a starting point, you can add a timespan and that will give you the new date.
st.ToString() will return "System.Nullable<Timespan>" because that is what a nullable type returns - it does not override the default Object.ToString implementation, so returns the type name.
If you want the string of the actual timespan, then you would need to do st.Value.ToString(), but you should be checking for null first (i.e. st.HasValue == true)
Edit: Also see #Sean's comment about how to output the Timespan without converting to a DateTime first.
Edit: Turns out I was slightly wrong - st.ToString() doesn't return the above. So see Sean's answer.
First convert Timespan to Datetime by adding TimeSpan to a base date of 00:00 hrs. Then on that dateTime derive the 12 hr format.
DateTime.Now.Date.Add(OpenTimeSpan).ToString(#"hh\:mm\:tt")
The Accepted Answer is wrong.
You cannot return AM/PM for a TimeSpan because it is only concerned with the length of Time,
not a Time of Day - hench the name, "TimeSpan".
Convert to a DateTime first before converting to a String:
string sTimeOfDay = new DateTime().Add(st).ToString("hh:mm tt");
Note: If your TimeSpan is nullable, then you will need to add Conditional Logic to Handle Nulls and pass in ts.Value instead of ts:
string sTimeOfDay = (st == null ? null : new DateTime().Add(st.value).ToString("hh:mm tt") );

How To Parse Date From any datetime format to dd/mm/yyyy?

i want to parse any datetime format to dd/MM/yyyy format.
here is my code
// dates i am providing are
// Sat, 01 Oct 2011 17:30:00 +0400
// and
// Sat, 01 October 2011 12:21:23 EST
Datetime dt = Convert.toDateTime(pubDate);
which is giving me following exception
The string was not recognized as a valid DateTime. There is an unknown word starting at index 32
any one guide me how can i parse any dateformat to a single one?
any help would be appreciated.
DateTime doesn't store dates in a "format" - it uses an internal representation. You need to parse a passed in string in order to get the correct value for the DateTime and when you want to display it you can then format it to whatever display.
Your best bet is to use TryParseExact supplying it with the exact format string. You need to use the custom Date and Time format strings with it.
Use the overload that takes a string[] of format strings - one for each date format.
In regards to the EST portion - the framework doesn't have support for named timezones. You may want to write a wrapper that converts named timezones to their equivalent but parseable form.
Untested (based on MSDN example):
string[] formats= {"ddd, dd/MMM/yyyy hh:mm:ss K",
"ddd, dd MMMM yyyy hh:mm:ss EST"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
Remove the 'EST' from the string and it should work.

Resources