.net DateTime Serialization Deserialization bug - c#

If you serialize and deserialize a DateTime using embedded .net JavaScriptSerializer, you get two different dates if you are in UTC+something !
Example (suppose you are in UTC+2 like I am now)
JavaScriptSerializer myJson = new JavaScriptSerializer();
DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);
//DO WHAT YOU NEED WITH IT...
DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 14:12:00 ! WRONG! IT's in UTC+0 ! Has 2 HOURS less !!!
So, when you get the deserialized date, it'll give you the UTC+0 value by default...!!
This is different from JavaScriptSerializer UTC DateTime issues because that article describes the difference in deserialization of different datetime data types, and provides a solution (.UtcDateTime) that doesn't fix the problem. In fact, trying to deserialize with .utcDateTime a serialized DateTime always gives you the wrong UTC+0 date...

There are two different solutions: either use ToLocalTime() when you deserialize OR use the Newtonsoft.Json.
So the same code, "fixed", in the first case should be:
JavaScriptSerializer myJson = new JavaScriptSerializer();
DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);
//DO WHAT YOU NEED WITH IT...
DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized).ToLocalTime();
Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 16:12:00 !!! CORRECT !
Otherwise, using Newtonsoft.Json (you first need to install it from nuGet, then add a "using Newtonsoft.Json" at the top), and use it like this:
DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = JsonConvert.SerializeObject(myDate);
//DO WHAT YOU NEED WITH IT...
DateTime myDateDes = JsonConvert.DeserializeObject<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//NO need to convert to LocalTime... it already gives you 2016-03-29 16:12:00 !!! CORRECT !
I hope this will be useful for someone else... I googled a lot and found nothing about this problem that only happens with Microsoft serializer...

Related

how to compare datetime value from database with textbox datetime value

I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.

Change the datetime format from '2014-03-11T14:10:46+11:00' to '20140311141046+11:00'

I am getting the dateTime value in the format 2014-03-11T14:10:46+11:00.
I need to change this into the format 20140311141046+11:00.
The method I am using right now is:
private string changeDateFormat()
{
DateTime dt = Convert.ToDateTime("2014-03-11T14:10:46+11:00");
return dt.ToString("yyyyMMddHHmmss");
}
It seems to be working fine but with one catch.
Instead of showing the output like 20140311141046+11:00,
the output is 20140311084046.
I think I need to pass the timezone too while converting to string. But I am blank on how to do that.
PS: This +11:00 is dynamic can can change in the input. Please suggest a generic solution/approach.
Since you parse it to DateTime you lost the offset part.
I would parse it to DateTimeOffset instead of DateTime and use K format specifier with it's format like;
var str = "2014-03-11T14:10:46+11:00";
var dto = DateTimeOffset.Parse(str);
return dto.ToString("yyyyMMddHHmmssK");
returns
20140311141046+11:00

Converting datetime format without using SAP RFC with C#

I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}

Coverting 9/13/2011 12:00:00 AM to 9/13/2011

I am getting this: 9/13/2011 12:00:00 AM
from my DB and I want to show like this:
9/13/2011
This is my code for this:
litDate.Text = Obj1.DueDate.ToString();
My DueDate is of this property:
public DateTime? DueDate { get; set; }
Try this:
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
Use the formatter "d", only if Obj1.Date is of type DateTime.
if(Obj1.DueDate.HasValue)
{
litDate.Text = Obj1.DueDate.Value.ToString("d");
}
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
This gives all the standard date format strings with examples.
Here is the example you want:
// Display using current (en-us) culture's short date format
DateTime thisDate = new DateTime(2008, 3, 15);
Console.WriteLine(thisDate.ToString("d"));
// Displays 3/15/2008
The answers that explicitly format the string should not be used in any case where you might have to internationalize the date. This answer uses the culture context of the user's computer.
litDate.Text = Obj1.Date.ToShortDateString();
Along with insta's answer, you can also use
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
http://www.csharp-examples.net/string-format-datetime/
EDIT: Now that you revised your question to a COMPLETELY DIFFERENT datatype, you need to learn how Nullables work. Check .HasValue, and if so, then .Value will be a DateTime, making all the rest of these answers relevant again.

.NET Date Add Days

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.
Try using DateTimeOffset.Parse. Then use AddDays or AddHours.
It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.
var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");
if you don't like the way "O" formats, you can use this:
var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")
This will 100% match to your format.
Example:
txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/
double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/
DateTime tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/
txt_total.Text = tom.ToString("MM/dd/yy")
Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.
That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.

Categories

Resources