java 使用GPS(LocationManager)如何获取当前时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4634053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the GPS (LocationManager) how To get the current Time?
提问by Jagan
I am developing one GPS Application. Which will send the location data to server for every one hour.
我正在开发一个 GPS 应用程序。它将每隔一小时将位置数据发送到服务器。
In this I am using following code:
在此我使用以下代码:
location.getLatitude();
location.getLongitude();
location.getTime();
with this code I am getting Latitude and Longitude correctly and Time also, but I am getting some 13 digits number instead of the time. I done some research on that, I found that is an seconds for of the current time.
使用此代码,我可以正确获取纬度和经度以及时间,但是我得到的是一些 13 位数字而不是时间。我对此做了一些研究,我发现这是当前时间的几秒钟。
so now I need to convert that 13 digit number in to the specific format.
所以现在我需要将该 13 位数字转换为特定格式。
回答by Matt Ball
Location#getTime()
returns "the UTC time of this fix, in milliseconds since January 1, 1970."
Location#getTime()
返回“此修复的 UTC 时间,以 1970 年 1 月 1 日以来的毫秒数为单位。”
This is exactly the same behavior as java.util.Date#getTime()
. I'm not clear on what you'd like to do with this time data, but if you'd like to convert the Location
's time into a java.util.Date
, you can do it like this:
这与java.util.Date#getTime()
. 我不清楚你想用这个时间数据做什么,但如果你想把Location
's 时间转换成 a java.util.Date
,你可以这样做:
long time = location.getTime();
Date date = new Date(time);
Now it is somewhat easier to work with. If you'd like to create a particular string output format of that date, use SimpleDateFormat
:
现在它更容易使用。如果您想创建该日期的特定字符串输出格式,请使用SimpleDateFormat
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String text = sdf.format(date);
System.out.println(text); // prints something like 2011-01-08 13:35:48
That said, if all you'd like to do is get the current time (which is what it sounds like you're trying to do) you don't need a Location
at all:
也就是说,如果您只想获取当前时间(这听起来像是您想要做的),则根本不需要Location
:
Date now = new Date();
That's it!
而已!
Does that help? If not, could you clarify what you're trying to do?
这有帮助吗?如果没有,你能澄清一下你想要做什么吗?
回答by bajarang
Date date = new Date(location.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDate= sdf.format(date);
System.out.println(myDate)
回答by Carlos Daniel Drury
String timestamp = parseDate(location.getTime().toDate());
public String parseDate(Date date){
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
return sdf.format(date).toString();
}