Android 显示时间

有规律的显示时间

private long currentTime;//当前系统时间
private long oldTime;//过去时间

//以七秒为周期显示时间
public String getTimes(){
        currentTime = System.currentTimeMillis();//获得当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");//格式化日期
        Date data = new Date();
        String str = sdf.format(data);
        if(currentTime-oldTime>=7*1000){//每隔7秒钟返回一下时间
            oldTime = currentTime;
            return str;
        }else{
            return "";
        }
    }
以下是在 Android 应用程序中显示当前时间和日期的示例代码: ```java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView txtTime = findViewById(R.id.txtTime); TextView txtDate = findViewById(R.id.txtDate); // 获取当前时间 Date currentTime = new Date(); // 设置时间格式 SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); // 显示时间和日期 txtTime.setText(timeFormat.format(currentTime)); txtDate.setText(dateFormat.format(currentTime)); } } ``` 在 XML 布局文件中,你需要添加两个 `TextView` 控件来显示时间和日期: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/txtTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="48sp"/> <TextView android:id="@+id/txtDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp"/> </LinearLayout> ``` 这样,你就可以在应用程序中显示当前时间和日期了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值