android - 在 Android 上将当前日期与时间分开
问题描述
我从谷歌得到当前日期,它给了我这样的回应:
date = **"Tue, 17 Mar 2020 12:37:44 GMT"**
但我只想要日期,所以我正在转换时间戳,但我无法得到想要的结果。
我在 onCreate() 方法中有这段代码:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
String date = response.getFirstHeader("Date").getValue();
Log.d("Date : ", date);
System.out.println("d :" + date);
timeStamp = date;
getTime();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.d("Response", e.getMessage());
} catch (IOException e) {
Log.d("Response", e.getMessage());
}
}
});
thread.start();
进入 getTime() 方法后,应用程序没有向我敬酒结果。这是代码:
private void getTime() {
String timeStampST = timeStamp;
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
String resultDate = null;
try {
date = fmt.parse(timeStampST);
SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy");
resultDate = fmtOut.format(date);
Toast.makeText(this, resultDate, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
注意:我想得到这样的日期
日期:2020 年 3 月 17 日,星期二
这就是为什么我要转换时间戳,但它不起作用。
解决方案
在我的问题上面,我使用的方法在getTime方法中不正确,所以我现在在 getTime 方法中所做的事情如下所述首先,我得到了 timeStamp 值。您可以通过在 Google 上将时间戳转换为日期来获取它。打开第一个链接并获取您的时间戳值。
在getTime()方法中,您只需要创建一个 Calendar 对象并在其上设置您的时间戳数据。您将时间戳数据放入您的日历对象,您可以使用DateFormat.format将其转换为字符串。像这样:
long timeStampValue = 1584517882L;
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timeStampValue * 1000L);
String date = DateFormat.format("yyyy-MM-dd", cal).toString();
Log.d("date: ", date);
推荐阅读
- javascript - 如何显示嵌套在数组中的对象的匹配描述?
- hyperledger-fabric - Hyperledger Blockchain 编写您的第一个应用程序 fabcar
- jquery - 使用 jQuery,更新数据元素属性的值
- node.js - 如何以只读模式获取 Draft js 中的链接?
- xml - Powershell:按元素索引将XML节点值选择为变量
- delphi - 如何垂直滚动 TFlowLayout 内容?
- python - 无法为多元 LSTM 获得正确的输入尺寸
- javascript - VueJS - 如何检查匹配值的数组?
- javascript - 为什么我未完成的 javascript 游戏在第三次死亡后崩溃?
- angularjs - 在 AngularJS 和 Bootstrap 的模式中文本输入不会自动完成的原因