Transfer DateTime to .NET WebAPI

问题内容:

I would like simply get Android current time and pass to .NET WebAPI. That is it. But there are many approaches…

I tried this one

Android side

String TimeOfRequest =  Long.toString(new Date().getTime());

.NET side

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
t = epoch.AddMilliseconds(Convert.ToInt64(locationItem.TimeOfRequest));

But it gives this result

0001-01-02 18:01:34.0366112

Please suggest about simplest approach to do it.

问题评论:

    
which date format you want?
    
@HemantParmar US MM/dd/yyyy HH:mm:ss
– Academy of Programmer
8 hours ago
    
I think it’s the best approach. It may due to new Android Date. Try java.uitl.Date: String TimeOfRequest = Long.toString(new java.util.Date().getTime());
1  
Transfer the date in ISO format, which is standard. YYYY-MM-DD HH:mm:ss. Then convert it to whichever format you like to display it.
1  
@OleV.V. ISO 8601: YYYY-MM-DDThh:mm:ssTZD. Right, I forgot the T and also TZD

答案:

答案1:

Try this:

private String formatDate(long milliseconds) /* This is your topStory.getTime()*1000 */ {
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliseconds);
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(tz);
    return sdf.format(calendar.getTime());
}

答案评论:

    
Passing a recognizable text rather than an unreadable millisecond value is a good idea. Now you are at it, I recommend a text in ISO 8601 format, like 2017-12-11T07:37:47.462Z.

答案2:

As mentioned, assume your API is correct, meaning you passing string from Android mobile to ASP.net API correctly.

String TimeOfRequest =  Long.toString(new Date().getTime());
//TimeOfRequest = "1512977867949" // For example

In your API:

// For example locationItem.TimeOfRequest = "1512977867949";
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var t= epoch.AddMilliseconds(Convert.ToInt64(locationItem.TimeOfRequest));

Console.WriteLine(t.ToString("MM/dd/yyyy HH:mm:ss")); // print "12/11/2017 07:37:47"
Console.WriteLine(t.GetType().ToString()); // print "System.DateTime"

答案评论:

原文地址:

https://stackoverflow.com/questions/47748096/transfer-datetime-to-net-webapi

Add a Comment