I write my logs to a text file as JSON. In the file the call obejct LogTime value is
"1378289277591".
*{"LogTime":"Date(1378290565240)"}*
Consider the code below:
Public Class Sync{
public async Task<CallModel> ConvertCallFileToCallObejct(string path)
{
try
{
using (var sr = new StreamReader(path))
{
string callText = await sr.ReadToEndAsync();
var call = new JavaScriptSerializer().Deserialize<CallModel>(callText);
return call;
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
I convert the Call File to Call Object:
var sync = new Sync();
CallModel call = sync.ConvertCallFileToCallObejct(e.FullPath).GetAwaiter().GetResult();
The problem is that Call.LogTime is 9/4/2013 10:29:25 AM but Using Chrome Console and new Date(1378290565240) the result is 9/4/2013 14:59:25 PM
What is the problem?
try below code
// JSON received from server is in string format
var jsonString = '{"date":1251877601000}';
//use JSON2 or some JS library to parse the string
var jsonObject = JSON.parse( jsonString );
//now you have your date!
alert( new Date(jsonObject.date) );
I'm not sure what your Time zone is but I would expect that its UTC datetime.
According to your profile, you live in Iran, where the timezone is UTC+3:30. However, in April, Iran uses daylight saving time so the real timezone is UTC+4:30.
This means that UTC time of 9/4/2013 10:29:25 AM is 9/4/2013 14:59:25 PM local time in Iran.
According to ECMA specification, the time given in your JSON string is treated as UTC time, and it is deserialized as such. You can check the return value of Call.LogTime expression which returns DateTimeKind.Utc. Thus, what you see in your C# code is UTC time.
Now, Chrome also sees this time as UTC time, however it seems to display it as local time, according to your timezone. I am not 100% sure, but I think that Chrome uses your list of preferred languages when choosing how to display date, so try to play with it - I have no idea what exactly it does, but I remember a similar problem when changing the language order affected how time was interpreted. OF course, it depends on what exactly you try to achieve - IMO, both values are correct, as it is the same time.
Related
I'm working on an ASP .NET Core 7 WebAPI, which handles Datetimes. I use Entity Framework Core 7 and Npgsql with Postgres.
As I want to save Datetimes without timezones to the database, I use the switch on the AppContext to enable it, according to Npgsql docs.
The issue is, in my integration test, everything is fine (date in response body is correct) until the date on the created record in the database, the Datetime object I get is shifted to 1 hour in the futur, event though, when I check in the database with a SQL Client, the date is correct. Here is the code of my integration test :
[Fact]
public async Task CreatePoll_CreatesPollInDb()
{
// Given
var createPollRequest = new CreatePollRequest
("Test Poll", DateTime.Now.AddDays(90), new List<DateTime> { DateTime.Now, DateTime.Now.AddDays(1) } );
// When
HttpResponseMessage response = await Client.PostAsJsonAsync("/api/polls", createPollRequest);
// Then
response.StatusCode.Should().Be(HttpStatusCode.Created);
var pollFromResponse = await response.Content.ReadFromJsonAsync<Poll>();
pollFromResponse.Id.Should().NotBeEmpty();
pollFromResponse.Name.Should().Be(createPollRequest.Name);
pollFromResponse.Dates.Should().BeEquivalentTo(createPollRequest.Dates);
pollFromResponse.ExpirationDate.Should().Be(createPollRequest.ExpirationDate);
Poll pollInDb = await DbContext.Polls.FirstAsync(record => record.Id == pollFromResponse.Id);
pollInDb.Name.Should().Be(createPollRequest.Name);
pollInDb.ExpirationDate.Should().Be(createPollRequest.ExpirationDate);
pollInDb.Dates.Should().BeEquivalentTo(createPollRequest.Dates);
}
The DbContext used in the test is not the one of the application, it is created specifically for the test as a separate fixture. The test runs against a real postgres database running in Docker.
I believe these solutions would answers your question
(.net) Unexpected offest when call DateTime.Today.AddDays
DateTime.Now giving incorrect time
I would like to recommend usingDateTime utcDate = DateTime.UtcNow;then change the datetime to users time. Like the 2nd link is recommending.
Ps. This problem is not new, and has been discussed many times before.
It's not a problem of EF or asp.net.core. It's a C# issue.
public class Example
{
public static void Main()
{
DateTime localDate = DateTime.Now;
String[] cultureNames = { "en-US", "en-GB", "fr-FR",
"de-DE", "ru-RU" };
foreach (var cultureName in cultureNames) {
var culture = new CultureInfo(cultureName);
Console.WriteLine("{0}: {1}", cultureName,
localDate.ToString(culture));
}
}
The example displays the following output:
en-US: 6/19/2015 10:03:06 AM
en-GB: 19/06/2015 10:03:06
fr-FR: 19/06/2015 10:03:06
de-DE: 19.06.2015 10:03:06
ru-RU: 19.06.2015 10:03:06
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.now?view=net-7.0
I've been using Protobuf-net as the serializer for a thick client application that's using Service Stack to communicate over HTTP. Our first customer with a lot of volume has started seeing errors when deserializing. We are sending DateTimeOffset types in some of our models, and so we created a surrogate that serializes the value as a string. From our logs, I can see when the error occurs this is the date value it's attempting to deserialize has an extra six characters at the end where the timezone offset is repeated:
8/9/2016 12:02:37 AM-7:00 -7:00
Here's the code for our surrogate.
[ProtoContract]
public class DateTimeOffsetSurrogate
{
[ProtoMember(1)]
public string DateTimeString { get; set; }
public static implicit operator DateTimeOffsetSurrogate(DateTimeOffset value)
{
return new DateTimeOffsetSurrogate { DateTimeString = value.ToString() };
}
public static implicit operator DateTimeOffset(DateTimeOffsetSurrogate value)
{
try
{
return DateTimeOffset.Parse(value.DateTimeString);
}
catch (Exception ex)
{
throw new Exception("Unable to parse date time value: " + value.DateTimeString, ex);
}
}
}
Once this date error has occurred, it won't correctly serialize/deserialize until the PC has rebooted. We have not been able to reproduce this error in a way that would allow us to debug and look at the rest of the message. Is this a situation that someone is familiar with? We were using version 2.0.0.640, and because of this issue I updated to 2.0.0.668 but the issue remains.
It looks as though the CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern is somehow getting messed up on the client's machine. I can reproduce the problem by adding the "K" format to the LongTimePattern:
var dateTime = DateTimeOffset.Parse(#"8/9/2016 12:02:37 AM-7:00");
var myCI = new CultureInfo("en-US");
myCI.DateTimeFormat.LongTimePattern = myCI.DateTimeFormat.LongTimePattern + " K";
Console.WriteLine(dateTime.ToString(myCI)); // Prints 8/9/2016 12:02:37 AM -07:00 -07:00
The string written is 8/9/2016 12:02:37 AM -07:00 -07:00 which is exactly what you are seeing.
It may be that there is a bug in your application which is setting the LongTimePattern somewhere. I can also reproduce the problem by doing:
Thread.CurrentThread.CurrentCulture = myCI;
Console.WriteLine(dateTime.ToString()); // Prints 8/9/2016 12:02:37 AM -07:00 -07:00
Or it may be that the client is somehow modifying the "Long time:" string in "Region and Language" -> "Additional settings..." dialog, which looks like (Windows 7):
If the client is doing this somehow, and the machine is on a domain, the format may get reset back on reboot which is exactly what you are seeing.
The client may be doing this manually (although, from experimentation, trying to append K manually on Windows 7 in the UI generates an error popup and then fails), or there may be some buggy 3rd party application doing it unbeknownst to you or them via a call to SetLocaleInfo.
You could log the value of LongTimePattern to try to trace the problem, but regardless you should modify your DateTimeOffsetSurrogate so that it serializes the DateTimeOffset in a culture-invariant format, preferably as specified by How to: Round-trip Date and Time Values: To round-trip a DateTimeOffset value:
[ProtoContract]
public class DateTimeOffsetSurrogate
{
[ProtoMember(1)]
public string DateTimeString { get; set; }
public static implicit operator DateTimeOffsetSurrogate(DateTimeOffset value)
{
return new DateTimeOffsetSurrogate { DateTimeString = value.ToString("o") };
}
public static implicit operator DateTimeOffset(DateTimeOffsetSurrogate value)
{
try
{
return DateTimeOffset.Parse(value.DateTimeString, null, DateTimeStyles.RoundtripKind);
}
catch (Exception ex)
{
throw new Exception("Unable to parse date time value: " + value.DateTimeString, ex);
}
}
}
Not only should this fix the bug you are seeing, it will also ensure that protocol buffers generated by your app in one region (say, the UK) can be parsed elsewhere (say, the US) with different cultural formatting for dates and times.
I'm trying to monitor system up time by using #snmp (Lextm.SharpSnmpLib.9.0.1) and C#.
Here's my code:
public int GetUptime()
{
var uptimeMessage = new GetNextRequestMessage(0, VersionCode.V1, new OctetString("public"),
new List<Variable>
{
new Variable(new ObjectIdentifier(Oids.SystemUpTime))
});
var response = uptimeMessage.GetResponse(10000, _agentEndPoint);
var ticks = response.Pdu().Variables[0].Data.ToString();
return int.Parse(ticks);
}
But i'm getting a CS0103 error when trying to get .Data property for a response of type TimeTicks.
Here's the Inspection Window of VS2015
If this is not a bug, how can i access raw ticks value using #snmp ?
By checking the source code of TimeTicks in this library you can see the ToString method in fact generates a string based in .NET TimeSpan. That's why when you try to parse it as int exceptions come.
As for this OID you already know the Data would be a TimeTicks you should cast to that type and then call ToUInt32.
I use asmx web service writes in c# over android device.
I make connection and when in some web method I need integer or string like input param,all work great, but problem is when web method need date, I try to send date in many format but always I have problem to get answer.
I need to send date object, or like string? It is possible that web service view date like something else?
This is method for "communication" with web service:
public void connectSOAP()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String dateStr = "04/05/2010";
Date dateObj=null;
SimpleDateFormat curFormater = new SimpleDateFormat("dd/mmm/yyyy");
try
{
dateObj = curFormater.parse(dateStr);
}
catch (java.text.ParseException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
request.addProperty("dtFrom",dateObj);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
if (envelope.getResponse() != null)
{
if (envelope.bodyIn instanceof SoapFault)
{
String str = ((SoapFault) envelope.bodyIn).faultstring;
Log.i("", str);
}
else
{
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
Log.d("WS", String.valueOf(resultsRequestSOAP));
}
};
}
catch (Exception e)
{
Log.d("WS","sss");
}
}
When i change web method(something with out date it work),I get response in log) But when is this way with date i just get catch ("sss" ) in log,i debug and find that it brake on:
androidHttpTransport.call(SOAP_ACTION, envelope);
But i not find anything about that in log except catch that i set...
For me this looks like the dateObj which you want to give to the webservice can not be parsed, thats why the exception occurre at this line:
androidHttpTransport.call(SOAP_ACTION, envelope);
But as your formatter has this format:
SimpleDateFormat curFormater = new SimpleDateFormat("dd/mmm/yyyy");
Maybe the (three!)"mmm" are causing the error?? I am pretty sure this will produce something like e.g. "Feb" for February and so on.. (e.g. "11/Feb/2014"):
Try something like:
SimpleDateFormat curFormater = new SimpleDateFormat("dd/mm/yyyy");
or
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Btw, to avoid localisation and interoperability issues, i often use DateTime objects accurately formatted to Strings for giving that objects over to WebService. Because many times i had problems by interoperability between e.g. .asmx Webservice and J2EE web service (e.g. the range of DateTime is not the same for J2EE and .NET and if it's a null/nil value you also run in troubles).
I have a simple webservice, which I want to access via a http post.
The webservice code is show below:
[WebMethod]
public int Insert(string userDate, string DeviceID)
{
bool output;
DateTime date;
output = DateTime.TryParse(userDate, out date);
if (!output)
{
// Throw an error
return -1;
}
int Device;
output = int.TryParse(DeviceID, out Device);
if (!output)
{
// Throw an Error
return -1;
}
UsersDatesBLL BLL = new UsersDatesBLL();
return BLL.Insert(Device, date);
}
I can access the service fine using internet explorer, the results are inserted to the database perfectly simply by calling: CountDownService.asmx/Insert?userDate=24/04/1980&DeviceID=3435
However when testing on Safari and Firefox the service always returns -1
Does anyone know the cause of this? Does Safari encode strings differently to IE?
Regards
Mick
Users can configure their UI language and culture in their browser. The browser passes this information as the Accept-Language HTTP header in requests to your webservice. That information may be used to set the "current culture" of the ASP.NET session that handles the request. It is available as the static property CultureInfo.CurrentCulture.
DateTime.TryParse will use that "current culture" to figure out which of the many datetime string formats it should expect - unless you use the overload where you explicitly pass a culture as the IFormatProvider. Apparently the browsers you are testing with are configured differently, so ASP.NET expects different datetime formats from each. If you want the datetimes to be parsed independently from the browser settings, then you should use CultureInfo.InvariantCulture as the format provider.
The first thing I would do as a debugging measure (assuming you can't just run a debugger on the server code) would be to make all three return paths return different values. That way you're not left guessing whether it was the DateTime.TryParse() call, the int.TryParse() call, or the BLL.Insert() call that failed.
If BLL.Insert() returns a -1 on failure, then I would change the first -1 to -3 and the second to -2. Like so:
output = DateTime.TryParse(userDate, out date);
if (!output)
{
// Throw an error
return -3; // ***** Changed this line
}
int Device;
output = int.TryParse(DeviceID, out Device);
if (!output)
{
// Throw an Error
return -2; // ***** Changed this line
}
I know it doesn't exactly answer the question, but it would at least help you track down which part is failing.
You are using the current culture to parse your DateTime and int values. The first thing to check is whether your various browsers are all configured to send the same culture to the web server in their HTTP request headers.
As a matter of style, you should avoid using culture-dependent formats for URL parameters. The most appropriate format to use is the fixed XML Schema format, like this:
[WebMethod]
public int Insert(string userDate, string DeviceID) {
DateTime date;
int device;
try {
date = XmlConvert.ToDateTime(userDate, XmlDateTimeSerializationMode.Local);
device = XmlConvert.ToInt32(DeviceID);
} catch (Exception) {
// Throw an error
return -1;
}
UsersDatesBLL BLL = new UsersDatesBLL();
return BLL.Insert(device, date);
}
And call it like this:
CountDownService.asmx/Insert?userDate=1980-04-24&DeviceID=3435
Another alternative is to use strongly-typed parameter values and let ASP.NET do the parsing for you, e.g.
[WebMethod]
public int Insert(DateTime userDate, int DeviceID) {
UsersDatesBLL BLL = new UsersDatesBLL();
return BLL.Insert(DeviceID, userDate);
}
DISCLAIMER - I have not tried this alternative myself, but it's worth a look, because it will make your life easier if you don't have to put parsing code into every web method.