Java converts seconds to standard Beijing Time

Source: Internet
Author: User

// The value returned by the server is usually in seconds, but the calculation requires milliseconds. * 1000l is required to obtain the correct date result.

Simpledateformat SDF = new simpledateformat ("yyyy-mm-dd hh: mm: SS"); // you can specify the date display format.

String time = SDF. format (new date (M * 1000l); // m is the converted value of the data returned from the server (usually in the form of a string returned by the server, need to be converted to int or long type)

The green time is based on 00:00:00, and the server returns the number of seconds from a certain time point to this benchmark (if it is a millisecond, it is better, you do not need to use * 1000l directly)

With the above time, you will find that it is eight hours less than the real time. The solution is to change the Java Default Time Zone to the UTC + 8 zone.

1. Add the following information to the system attributes:

system.setProperty("user.timezone", "Asia/Shanghai");

2. Change the default time zone to our time zone:

TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");        TimeZone.setDefault(tz);

The following time is the time you get from the server, and times is the date format you want.

Public String pasertime (INT time) {system. setproperty ("user. timezone "," Asia/Shanghai "); timezone TZ = timezone. gettimezone ("Asia/Shanghai"); timezone. setdefault (Tz); simpledateformat format = new simpledateformat ("yyyy-mm-dd hh: mm: SS"); string times = format. format (new date (time * 1000l); system. out. print ("Date Format ---->" + times); Return times ;}


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.