Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

android - Converting seconds to date time String

I have seconds from epoch time and want to convert it to Day-Month-Year HH:MM
I have tried following but it gives me wrong value.

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......

Above code is not working properly am i doing anything wrong here.

For example if seconds = 1299671538 then it generates time string as Friday, December 12, 1969 which is wrong it should display Wednesday, March 09, 2011

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example if seconds = 1299671538 then it generates time string as Friday, December 12, 1969 which is wrong it should display Wednesday, March 09, 2011

You have integer overflow. Just use the following (notice "L" after 1000 constant):

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000L);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......

or better use SimpleDateFormat class:

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm");
String dateString = formatter.format(new Date(seconds * 1000L));

this will give you the following date string for your original seconds input: Wednesday, March 9, 2011 13:52


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...