Win10 UWP Unix timestamp timestamp turn datetime

Source: Internet
Author: User
Tags creative commons attribution

Original: Win10 UWP unix timestamp timestamp to DateTime

Sometimes you need to turn the UNIX timestamp of the network into a DateTime for C #, how can the UWP be converted?

The conversion function can use the following code

        privatestaticUnixTimeStampToDateTime(long unixTimeStamp)        {            new System.DateTime(1970110000);            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);            return dtDateTime;        }

How to transfer from DateTime to UNIX timestamp, using the following code

       publicstaticlongToUnixTimestamp(DateTime time)        {            varnew DateTime(197011000, time.Kind);            var unixTimestamp = System.Convert.ToInt64((time - date).TotalSeconds);            return unixTimestamp;        }

If it's such a simple code, I wouldn't write a blog specifically.

I encountered a problem, I got the JSON, the time is UNIX timestamp, I need to put a long time to convert DateTime, but I do not like to use when the conversion, can write, all the Unix timestamp automatically converted to D Atetime?

In code, the process is:

    1. JSON conversion to get objects

    2. object to be converted, but at this point it is discovered that a class needs to be re-written, and the class is different from the original class except for the same type. It looks like the code isn't elegant.

  varjson=NewJson (" {"Created_utc": 1498037127}");//The following classes are all I wrote for the sake of illustration, actually can't run in vsFoo Foo=json. Convert ();//json conversion to get objects  //But at this time the type of Foo is   class Foo {Long CREATED_UTC; }//And what is actually needed is   class Foo1 {DateTime CREATED_UTC; }//Then you need to write something to convert Foo to Foo1, it doesn't look elegant .  //Then directly read Json for modification No, the answer is no, because if I have a class that is   class Foo {Long CREATED_UTC;List<Foo>List;//He is an array of which I do not know how many may exist}//If this is the case, you need to read JSON, it takes a long time to write  //After writing, found that there is another similar thing, he also need this, then the programmer will have to do this, no technical content of things

After reading the above question, is it not thought that JSON has an elegant way to do, yes, he can write his own converter.

I found a simple way to convert the DateTime and Unix timestamp to each other directly from the Json conversion process.

Problem in: https://stackoverflow.com/q/44643498/6116637

Here's how to fix it. The following need to use the advanced usage of jsonconverter. First you need to use Nuget to download the JSON library, of course, search json download the first one.

Then create a class for type conversion, which means converting from one type of input to one type of output

For more advanced JSON usage, see: http://www.cnblogs.com/yanweidie/p/4605212.html

class UnixConvert : JsonConverter

As you can see, the created type must be re-three functions

WriteJsonReadJsonCanConvert

It is easy to know that it WriteJson is the conversion from an existing class to JSON, and what is required for the type to be encountered. ReadJsonwhen you convert from a JSON to a class, you encounter how JSON needs to be transformed. CanConvertwhether the current input supports conversions.

Of course these functions are for attributes, so reading a value is fine.

The Unix timestamp need to be converted to DateTime at first, so it is a string-to-attribute from JSON.

Write the code is ReadJson , then began to write this function

        publicoverrideobjectReadJsonobject existingValue, JsonSerializer serializer)        {            longlong.Parse(reader.Value.ToString());            return UnixTimeStampToDateTime(unixTimeStamp);        }

This is the code of the transformation, it looks very simple.

Read a value, turn him to a long, and then use the function above to convert DateTime, why it is used here is a long. Parse, because the JSON is guaranteed to be correct, if the JSON is not correct, then it is good practice to tell the error directly.

And the read function, in turn, takes the property to the JSON string, which can be seen from the parameter, the value to be converted is value, where the strong turn is used, because it knows his type. Writer can write directly to many types

      publicoverridevoidWriteJsonobjectvalue, JsonSerializer serializer)        {            varvalue);            writer.WriteValue(time);        }

It looks like it's written, but the last function only needs to return true, and it doesn't need to do anything for the time being.

Start writing an example to test.

Before I test, I'm going to write out all the code for the conversion class above.

Class Unixconvert:jsonconverter { Public Override void Writejson(Jsonwriter writer,Object value, Jsonserializer Serializer) {varTime = Tounixtimestamp (DateTime)value); Writer.        WriteValue (time); } Public Override Object Readjson(Jsonreader Reader, Type ObjectType,ObjectExistingvalue, Jsonserializer Serializer) {LongUnixtimestamp =Long. Parse (reader. Value.tostring ());returnUnixtimestamptodatetime (Unixtimestamp); } Public Override BOOL Canconvert(Type ObjectType) {return true; }Private StaticDatetimeUnixtimestamptodatetime(LongUnixtimestamp) {System.DateTime dtdatetime =NewSystem.DateTime (1970,1,1,0,0,0,0); Dtdatetime = Dtdatetime.addseconds (Unixtimestamp);returnDtdatetime; } Public Static Long Tounixtimestamp(DateTime time) {varDate =NewDateTime (1970,1,1,0,0,0, time. Kind);varUnixtimestamp = System.Convert.ToInt64 ((time-date). TotalSeconds);returnUnixtimestamp; }    }

The test is to write a class, convert it to JSON, and then use JSON to turn the class to see if the result is the same.

   class Foo    {        [JsonConverter(typeof(UnixConvert))]        publicsetget; }    }             new Foo()            {                created_utc = DateTime.Now            };            var str = JsonConvert.SerializeObject(foo);            foo = JsonConvert.DeserializeObject<Foo>(str);

The conversion gets the JSON as {"created_utc":1498037127}

Because I use DateTime.Now, so if you use this class, the result may be different from what I get.

You can see the same result from the JSON transformation and the properties of the created class, so this method can be used.

https://stackoverflow.com/questions/44643498/convert-unix-timestamp-to-normal-date-uwp/44650513#44650513


This work is licensed under the Creative Commons Attribution-NonCommercial use-Share 4.0 International license agreement in the same way. Welcome to reprint, use, republish, but be sure to keep the article Attribution Lindesi (including Link: http://blog.csdn.net/lindexi_gd), not for commercial purposes, based on the modified works of this article must be issued with the same license. If you have any questions, please contact me.

Win10 UWP Unix timestamp timestamp turn datetime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.