I am using Web API2 to communicate with mobile.
Datetime in response was always containing T eg. [2018-09-26T01:30:37.967] which is UTC. To remove it I converted DateTime zone to iso like this
IsoDateTimeConverter converter = new IsoDateTimeConverter
{
DateTimeStyles = DateTimeStyles.AdjustToUniversal,
DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
};
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);
Now another problem appeared that Input parameter does not take DateTime without T.
Previously it was working [2018-09-26 01:30:37.967] but not it stopped
I tried with this [2018-09-26T01:30:37.967] it worked. but I don't want it.
Web API should work with [2018-09-26T01:30:37.967] both for incoming and outgoing.
Waiting for help
With little change it worked. just changed yyyy-MM-dd HH:mm:ss to yyyy-MM-dd HH:mm:ss.fff
IsoDateTimeConverter converter = new IsoDateTimeConverter
{
DateTimeStyles = DateTimeStyles.AdjustToUniversal,
DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"
};
Related
I want to change DateTime now to the Format {"MM/dd/yyyy"} using this code.
string.Format("{0:MM:dd:yyyy}", DateTime.Now)
and saving it.
after getting saved string I get DateTime in format {"MM/dd/yyyy"} . Now I want to convert it in another format so I can Parse to DateTime. when I try to parse MM/dd/yyyy to DateTime got an error
"FormatException: String was not recognized as a valid DateTime."
Thanks in Advance.
You can rather use DateTime.ParseExact which allows you to specify the exact date format you are expeting the input to have.
For example
var now = DateTime.Now;
Debug.Log(now.ToString("dd.MM.yyyy"));
var example1 = now.ToString("MM/dd/yyyy");
Debug.Log(example1);
var readTime1 = DateTime.ParseExact(example1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime1.ToString("dd.MM.yyyy"));
var example2 = now.ToString("dd/MM/yyyy");
Debug.Log(example2);
var readTime2 = DateTime.ParseExact(example2, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime2.ToString("dd.MM.yyyy"));
See Fiddle
The format is only relevant for display
If you save it in a C# DateTime variable, there is no "format" when saving it, this DateTime is a struct data type which is universal and not bound to any specific format
If you want to use a specific format for parsing, you can use:
// Parse date and time with custom specifier.
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
DateTime myDate = DateTime.ParseExact(dateString, format, provider);
You can use CultureInfo to optimize your format for you needs
If there is a need to save it as "MM/dd/yyyy", your should save it as string
best regards
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.
I am using asp net core with entity framework. I have a datetimepicker which i am using as calendar. I have customize its format using jquery like this.
$('.datepicker').datetimepicker({
format: 'yyyy-mm-dd'
});
This shows the date forma to user.
and then converting it to C# datetime I am saving it in database in same format.Every thing is correct till now.
Now on my next visit this page has to be pre-filled if data is there. This time on the textbox of calendar it is showing some thing like 0007/02/19 where as the date that i entered is 1993/07/02 and the date that is saved in database is 7/2/1993. I tried using
String DateString = Convert.ToString(ProfileDetails.DateOfBirth);
IFormatProvider culture = new CultureInfo("en-US");
DateTime dateVal = DateTime.ParseExact(DateString, "MM/dd/YYYY", CultureInfo.InvariantCulture);
DateTime date = Convert.ToDateTime(dateVal);
user.DateOfBirth = dateVal;
this but was getting error string is not in valid datetime format. In my modal I have defined date as datetime. I am not getting the solution. Can any one gives me the correct way to complete that.
Cuz you are using MM/dd/YYYY instead MM/dd/yyyy
Working code:
String DateString = Convert.ToString("07/02/1993");
IFormatProvider culture = new CultureInfo("en-US");
DateTime dateVal = DateTime.ParseExact(DateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
I know this question has been asked before and resolved using various methods.
I am converting a value from a string to a DateTime.
Throughout the project I have used the same CultureInfo, all strings that where converted to date where done using Convert.ToDateTime(), but now there is one text field that refuses to convert.
I have tried:
string date = "27/02/2013";
string startdated = (Convert.ToDateTime(date)).ToString("yyyy/MM/dd");
(converts to datetime and changes it back to sting in my required format. This works fine on everything else)
even
Datetime dt = Convert.toDateTime(date); doesn't work
DateTime.ParseExact(date, "yyyy/MM/dd", format); doesn't work
And all give me the same error "String was not recognized as a valid DateTime.". i receive my date value from a textbox with an ajax calender extender (CalendarExtender.Format = "dd/MM/yyyy" done for display purposes,this also works everywhere else i.e "dd/MM/yyyy" for display and "yyyy/MM/dd" for procedure) except this final value which simply will not change. Everthing is done via my machine with no external servers
Your input string is not in the same format as the format you provde DateTime.ParseExact with.
For this to work
DateTime.ParseExact(date, "yyyy/MM/dd", format);
You have to enter the date in year/month/day format. But your string is in day/month/year.
This should work better.
string date = "27/02/2013";
DateTime parsedDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Your date is date = "27/02/2013"; and your current format (in DateTime.ParseExact) is "yyyy/MM/dd", It should be:
"dd/MM/yyyy"
So the following code should work.
string date = "27/02/2013";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can also use the format "d/M/yyyy" which would take care of single or double digit date/month.
I have some JavaScript code that I'm trying to pass to my web service. My JavaScript code is supposed to send a date in UTC format. Locally, the time that I generated my code at was at 12:30:43 pm. When I executed my JavaScript code, the following date/time was generated:
2012-06-03T20:30:43.000Z
That date/time was generated from this code:
var now = new Date();
var utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
When I pass the date/time from JavaScript back to my web service, it is serialized as shown here:
20120603163043
That looks correct to me at this point. I then need to take that string and convert it to a date/time in C#. In an attempt to do that, I'm using the following C# code:
DateTime _value = DateTime.MinValue;
DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _value)
When that happens, I get the following date/time.
6/3/2012 12:30:43 PM
What am I doing wrong? I was expecting the date/time to be 6/3/2012 4:30:43 PM
The result you get is correct, but please check the Kind property of your DateTime. You'll notice it's not set to UTC but to Local.
You can use DateTimeStyles.AdjustToUniversal to generate a DateTime with Kind set to UTC.
DateTime dateTime;
DateTime.TryParseExact(
value,
"yyyyMMddHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out dateTime);
See it working on ideone.
If you just want to serialize using (e.g. webAPI) I find JS toISOString very useful and compatible.
//JAVASCRIPT
var d = new Date();
$toPut.dateTime = d.toISOString();
$toPut.put()
//C#
[Put("/setup/dateTime"), HttpPut]
public HttpResponseMessage SetDateTime([FromBody]DateTime dateTimeSettings )
That way you can keep your data structure and not deal with parsing.
You must pass date parameter to web service as UTC format and then use TryParse method to convert it to C# date object.
Try this:
//Javascript
var now = new Date(); //just like: 'Thu, 21 Mar 2013 12:44:40 GMT'
var utcNowString = now.toUTCString(); //pass this parameter to your web service
And this is C# code:
DateTime date;
DateTime.TryParse(jsDateString, out date); //parsed as: '21.03.2013 14:44:40'
Hope this helps.