文章选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术。本文探讨Android显示当前日期和时间的方法。

问题:

RBADS

如何在Android应用中显示当前日期和时间?

答案:

ordid

这个有多种解决方法。我假设你想把当前日期和时间放在TextView上。

1
2
3
4
String currentDateTimeString = DateFormat.getDateTimeInstance().format(newDate());
 // textView is the TextView view that should display it
textView.setText(currentDateTimeString);

文档里可以阅读更多,点击 here 。你可以在那里读到更多信息,来更改用于转换的格式。

user647826

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class XYZ extends Activity {
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
 
        Calendar c = Calendar.getInstance();
        System.out.println("Current time => "+c.getTime());
 
        SimpleDateFormat df = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = df.format(c.getTime());
        // formattedDate have current date/time
        Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
 
 
      // Now we display formattedDate value in TextView
        TextView txtView = newTextView(this);
        txtView.setText("Current Date and Time : "+formattedDate);
        txtView.setGravity(Gravity.CENTER);
        txtView.setTextSize(20);
        setContentView(txtView);
    }
 

Prashant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    setContentView(R.layout.main);
    Thread myThread = null;
 
    Runnable runnable = newCountDownRunner();
    myThread= newThread(runnable);  
    myThread.start();
 
}
 
public void doWork() {
    runOnUiThread(newRunnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
                    Date dt = newDate();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":"+ minutes +":"
+ seconds;
                    txtCurrentTime.setText(curTime);
            }catch(Exception e) {}
        }
    });
}
 
 
class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try{
                doWork();
                    Thread.sleep(1000);
                } catch(InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}

Dave Webb

要展示当前时间, AnalogClockViewDigitalClockView是明智的选择。

例如下面的布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0"
encoding=
"utf-8"?>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
 
    <AnalogClock
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
 
    <DigitalClock
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"/>
</LinearLayout>

看起来是这个样子:

fred

我自己的展示方法:

1
2
3
4
5
6
7
Calendar c = Calendar.getInstance();
 
String sDate = c.get(Calendar.YEAR) + "-"
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH)
+ " at " + c.get(Calendar.HOUR_OF_DAY)
+ ":" + c.get(Calendar.MINUTE);

ZuzooVn

如果你想用特定的模式展示日期和时间,可以用这个:

1
2
Date d = newDate();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());

Thomas V J

1
2
3
4
Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-"+ month+"-"
+ c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

这个展示日期的格式是 2010-05-24T18:13:00

chetan

这能显示当前时间和日期:

1
2
3
4
5
6
7
public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return
dt;
}

Hemant

如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
SimpleDateFormat dateFormat = newSimpleDateFormat(
                "yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        System.out.println("time => "+ dateFormat.format(cal.getTime()));
 
        String time_str = dateFormat.format(cal.getTime());
 
        String[] s = time_str.split(" ");
 
        for(int i = 0; i < s.length; i++) {
             System.out.println("date  => "+ s[i]);
        }
 
        int year_sys = Integer.parseInt(s[0].split("/")[0]);
        int month_sys = Integer.parseInt(s[0].split("/")[1]);
        int day_sys = Integer.parseInt(s[0].split("/")[2]);
 
        int hour_sys = Integer.parseInt(s[1].split(":")[0]);
        int min_sys = Integer.parseInt(s[1].split(":")[1]);
 
        System.out.println("year_sys  => "+ year_sys);
        System.out.println("month_sys  => "+ month_sys);
        System.out.println("day_sys  => "+ day_sys);
 
        System.out.println("hour_sys  => "+ hour_sys);
        System.out.println("min_sys  => "+ min_sys);

原文链接:Display the current time and date in an Android application

Android多种方法显示当前日期和时间的更多相关文章

  1. CentOS下多种方法显示文本行号

    一.创建文本文件 ..}| >test.txt cat test.txt 二.多种方法显示行号 方法一:nl命令(注意:空行不显示行号) [root@WT data]# nl test.txt ...

  2. 【Android自学日记】使用DatePicker以及TimePicker显示当前日期和时间

    DatePicker 1.获取一个日历对象: Calendar cal=Calendar.getInstance(); 2.获取当前日期及时间: int year=cal.get(Calendar.Y ...

  3. WdatePicker文本框显示当前日期和时间限制<My97DatePicker两个日期范围不超过30天,第一个小于第二个,都不大于当前日期 >

    My97DatePicker是很不错的一个日期选择插件,体积只有几十k但是功能非常强大.官网:http://www.my97.net/ 能满足很多苛刻的要求. WdatePicker文本框显示当前日期 ...

  4. Android 使用DatePicker以及TimePicker显示当前日期和时间

    课程内容1.介绍DatePicker和TimePicker两种实现动态输入日期和事件的功能2.介绍DatePickerDialog和TimePickerDialog来年耕种实现动态输入日期和事件的对话 ...

  5. 完整显示当前日期和时间的JS代码(2007年2月25日星期日正午12:42:48)

    代码演示效果为“2007年2月25日星期日正午12:42:48”. 使用方法:将下面的JS代码放到你想要显示的页面中(支持HTML页面),然后在你想要显示时间的位置插入下面的代码即可 <div ...

  6. 完整显示当前日期和时间的JS代码

    代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...

  7. Android 自学之日期DatePicker、时间TimePicker选择器

    日期(DatePicker).时间(TimePicker)是两个比较易用的控件,他们都是从帧布局FrameLayout派生而出的:他们在FrameLayout的基础上提供了一些方法来获取当前用户所选择 ...

  8. Android获取系统时间的多种方法

    Android中获取系统时间有多种方法,可分为Java中Calendar类获取,java.util.date类实现,还有android中Time实现. 现总结如下: 方法一: ? 1 2 3 4 5 ...

  9. jquery easyui datebox 时间控件默认显示当前日期的实现方法

    jquery easyui datebox 时间控件默认显示当前日期的实现方法 直接class easyui-datebox后添加一个value="true"就可以

随机推荐

  1. sql中distinct和order by问题的解决方案

    需求:根据PID字段对数据去重,根据Sort字段排序,需要显示这个两个字段. 如图,这是原始数据,先排序: 排序后发现两个项是重复的,需要去除一个, 因为Distinct对检查Select里面的每一列 ...

  2. ES使用C#添加和更新文档

    ElasticSearch 使用C#添加和更新文档 这是ElasticSearch 2.4 版本系列的第四篇: 第一篇:ES1:Windows下安装ElasticSearch 第二篇:ES2:Elas ...

  3. 【学习总结】GirlsInAI ML-diary day-6-String字符串

    [学习总结]GirlsInAI ML-diary 总 原博github链接-day6 认识字符串 字符串的性质 字符串的玩法 1-字符串就是字符的序列 序列,代表字符串是有顺序的!这里很重要. 比如我 ...

  4. 简单封装mongodb

    首先安装mongodb  npm i mongodb --save 简单封装,在modules目录下新建db.js var MongoClient=require('mongodb').MongoCl ...

  5. vue 开发依赖安装

    安装element-ui yarn add element-ui --save 使用element-ui main.js import Vue from 'vue'; import ElementUI ...

  6. SpringMVC controller 时间 T

    Spring MVC 之 处理Date类型 - carl.zhao的专栏 - CSDN博客https://blog.csdn.net/u012410733/article/details/727730 ...

  7. Error Boundaries 错误边界

    错误边界是用于捕获其子组件树 JavaScript 异常,记录错误并展示一个回退的 UI 的 React 组件,而不是整个组件树的异常.错误边界在渲染期间.生命周期方法内.以及整个组件树构造函数内捕获 ...

  8. 【学亮开讲】Oracle内外连接查询20181119

    --内连接查询 --需求:查询显示业主编号.业主名称.业主类型名称 select os.id 业主编号,os.name 业主名称,ot.name 业主类型名称 from t_owners os,t_o ...

  9. 大白跟着“菜鸟”学node——同名事件

    若存在两个同名事件,触发事件时,两个事件监听器的回调函数会被按次序先后调用. 实例来自菜鸟教程: var events=require('events'); var emitter=new event ...

  10. 防火墙禁ping:虚拟机ping不通主机,但主机可以ping虚拟机

    现象:刚装的centos6.6,配置好网络却发现ping不通主机,主机却ping通虚拟机: 解决方法: 1.最简单的方法就是:关闭防火墙.但一直关闭防火墙也不是个办法,会遇到很多安全问题,建议下一个方 ...