首页 文章

获取Android上的当前时间和日期

提问于
浏览
931

如何在Android应用中获取当前时间和日期?

30 回答

  • 29
    final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
    
    textView.setText(""+mDay+"-"+mMonth+"-"+mYear);
    
  • 3

    对于自定义的时间和日期格式:

    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
        String cDateTime=dateFormat.format(new Date());
    

    输出如下格式:2015-06-18T10:15:56-05:00

  • 4

    你也可以使用android.os.SystemClock . 例如,当手机处于睡眠状态时,SystemClock.elapsedRealtime()将为您提供更准确的时间读数 .

  • 299

    如果你需要当前日期,

    Calendar cc = Calendar.getInstance();
    int year=cc.get(Calendar.YEAR);
    int month=cc.get(Calendar.MONTH);
    int mDay = cc.get(Calendar.DAY_OF_MONTH);
    System.out.println("Date", year+":"+month+":"+mDay);
    

    如果你需要当前时间,

    int mHour = cc.get(Calendar.HOUR_OF_DAY);
     int mMinute = cc.get(Calendar.MINUTE);
     System.out.println("time_format"+String.format("%02d:%02d", mHour , mMinute ));
    
  • 30
    Time time = new Time();
    time.setToNow();
    System.out.println("time: " + time.hour+":"+time.minute);
    

    例如,这将给你12:32 .

    记得导入android.text.format.Time;

  • 35

    对于那些可能更喜欢自定义格式的用户,您可以使用:

    DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
    String date = df.format(Calendar.getInstance().getTime());
    

    而您可以使用DateFormat模式,例如:

    "yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
    "hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
    "EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
    "yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
    "yyMMddHHmmssZ"-------------------- 010704120856-0700
    "K:mm a, z" ----------------------- 0:08 PM, PDT
    "h:mm a" -------------------------- 12:08 PM
    "EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
    
  • 7

    您只需使用以下代码:

    DateFormat df = new SimpleDateFormat("HH:mm"); //format time
     String time = df.format(Calendar.getInstance().getTime());
    
     DateFormat df1=new SimpleDateFormat("yyyy/MM/dd");//foramt date
     String date=df1.format(Calendar.getInstance().getTime());
    
  • 478
    Time now = new Time();
    now.setToNow();
    

    试试这个也适合我 .

  • 45
    SimpleDateFormat dateFormat = new SimpleDateFormat("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);
    
  • 7

    您可以使用以下方式获取日期:

    Time t = new Time(Time.getCurrentTimezone());
    t.setToNow();
    String date = t.format("%Y/%m/%d");
    

    这将以一个很好的形式给你一个结果,如在这个例子中:“2014/02/09” .

  • 23

    这是一种有助于获取日期和时间的方法:

    private String getDate(){
        DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
        String date=dfDate.format(Calendar.getInstance().getTime());
        DateFormat dfTime = new SimpleDateFormat("HH:mm");
        String time = dfTime.format(Calendar.getInstance().getTime());
        return date + " " + time;
    }
    

    您可以调用此方法并获取当前日期和时间值:

    2017/01//09 19:23
    
  • 11

    您可以使用以下代码:

    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String strDate = sdf.format(c.getTime());
    

    输出:

    2014-11-11 00:47:55
    

    您还可以从here获得 SimpleDateFormat 的更多格式选项 .

  • 11

    实际上,使用 Time.getCurrentTimezone() 设置设备上的当前时区更安全,否则您将获得UTC的当前时间 .

    Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    

    然后,您可以获得所需的所有日期字段,例如:

    textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
    textViewMonth.setText(today.month + "");              // Month (0-11)
    textViewYear.setText(today.year + "");                // Year 
    textViewTime.setText(today.format("%k:%M:%S"));  // Current time
    

    有关所有详细信息,请参阅android.text.format.Time class .

    UPDATE

    正如许多人指出的那样,谷歌表示这个类有很多问题,不应该再使用了:

    此类有许多问题,建议使用GregorianCalendar代替 . 已知问题:由于历史原因,在执行时间计算时,所有算术当前都使用32位整数进行 . 这限制了从1902年到2037年可以表示的可靠时间范围 . 有关详细信息,请参阅维基百科关于2038年问题的文章 . 不要依赖这种行为;它可能会在未来发生变化 . 在不存在的日期上调用switchTimezone(String),例如由于DST转换而跳过的挂起时间,将导致1969年的日期(即1970年1月1日以前的-1或1秒) . 大多数格式化/解析都采用ASCII文本,因此不适合与非ASCII脚本一起使用 .

  • 12

    有几个选项,因为Android主要是Java,但是如果你想在textView中编写它,下面的代码可以解决这个问题:

    String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
    
    // textView is the TextView view that should display it
    textView.setText(currentDateTimeString);
    
  • 4

    对于当前日期和时间,请使用:

    String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
    

    哪个输出:

    Feb 27, 2012 5:41:23 PM
    
  • 52

    如果要以特定模式获取日期和时间,可以使用以下内容:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String currentDateandTime = sdf.format(new Date());
    
  • 9

    尝试使用以下代码:

    Date date = new Date();
     SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());  
     String currentDate = dateFormatWithZone.format(date);
    
  • 123

    很简单,您可以剖析时间来获取当前时间的单独值,如下所示:

    Calendar cal = Calendar.getInstance(); 
    
      int millisecond = cal.get(Calendar.MILLISECOND);
      int second = cal.get(Calendar.SECOND);
      int minute = cal.get(Calendar.MINUTE);
            //12 hour format
      int hour = cal.get(Calendar.HOUR);
            //24 hour format
      int hourofday = cal.get(Calendar.HOUR_OF_DAY);
    

    日期相同,如下:

    Calendar cal = Calendar.getInstance(); 
    
      int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
      int year = cal.get(Calendar.YEAR);
      int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
      int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);
    
  • 8

    Try this code it display current date and time

    Date date = new Date(System.currentTimeMillis());
     SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
                             Locale.ENGLISH);
     String var = dateFormat.format(date));
    
  • 21

    尝试这种方式下面给出所有格式以获取日期和时间格式 .

    Calendar c = Calendar.getInstance();
        SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
        String datetime = dateformat.format(c.getTime());
        System.out.println(datetime);
    
  • 4

    您应该根据新的API使用Calender类 . 现在不推荐使用日期类 .

    Calendar cal = Calendar.getInstance();
    
    String date = ""+cal.get(Calendar.DATE)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR);
    
    String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
    
  • 7

    你可以使用:

    import java.util.Calendar
    
    Date currentTime = Calendar.getInstance().getTime();
    

    日历中有很多常量可供您使用 .

    编辑:
    检查Calendar class documentation

  • 1
    SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
    SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
    SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
    SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
    SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
    SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
    SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");
    
    
    String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
    String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
    String currentDateandTime = sdf1.format(new Date());     //30.06.09
    String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
    String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
    String currentDateandTime = sdf4.format(new Date());     //8:29 PM
    String currentDateandTime = sdf5.format(new Date());     //8:29
    String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
    String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
    String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM
    

    日期格式模式

    G   Era designator (before christ, after christ)
    y   Year (e.g. 12 or 2012). Use either yy or yyyy.
    M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
    d   Day in month. Number of d's determine length of format (e.g. d or dd)
    h   Hour of day, 1-12 (AM / PM) (normally hh)
    H   Hour of day, 0-23 (normally HH)
    m   Minute in hour, 0-59 (normally mm)
    s   Second in minute, 0-59 (normally ss)
    S   Millisecond in second, 0-999 (normally SSS)
    E   Day in week (e.g Monday, Tuesday etc.)
    D   Day in year (1-366)
    F   Day of week in month (e.g. 1st Thursday of December)
    w   Week in year (1-53)
    W   Week in month (0-5)
    a   AM / PM marker
    k   Hour in day (1-24, unlike HH's 0-23)
    K   Hour in day, AM / PM (0-11)
    z   Time Zone
    
  • 195

    tl;博士

    Instant.now()  // Current moment in UTC.
    

    …要么…

    ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone
    

    详情

    其他答案虽然正确,但已经过时了 . 旧的日期时间类已被证明设计糟糕,令人困惑,并且很麻烦 .

    java.time

    这些旧类已被java.time框架取代 .

    这些新类的灵感来自于非常成功的Joda-Time项目,该项目由JSR 310定义,并由ThreeTen-Extra项目扩展 .

    Oracle Tutorial .

    瞬发

    InstantUTC中时间轴上的一个时刻,分辨率高达nanoseconds .

    Instant instant = Instant.now(); // Current moment in UTC.
    

    时区

    应用时区(ZoneId)获取ZonedDateTime . 如果省略时区,则会隐式应用JVM的当前默认时区 . 最好明确指定所需/预期的时区 .

    continent/region 的格式使用proper time zone names,例如America/MontrealEurope/BrusselsAsia/Kolkata . 切勿使用诸如 ESTIST 之类的3-4字母缩写,因为它们既不是标准化也不是唯一的 .

    ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
    ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
    

    生成字符串

    您可以轻松生成 String 作为日期时间值的文本表示 . 您可以使用标准格式,自己的自定义格式或自动本地化格式 .

    ISO 8601

    您可以调用 toString 方法来使用通用且合理的ISO 8601标准格式化文本 .

    String output = instant.toString();
    

    2016-03-23T03:09:01.613Z

    请注意,对于 ZonedDateTimetoString 方法通过在方括号中附加时区名称来扩展ISO 8601标准 . 非常有用和重要的信息,但不是标准的 .

    2016-03-22T20:09:01.613-08:00 [America / Los_Angeles]

    自定义格式

    或者使用DateTimeFormatter类指定您自己的特定格式模式 .

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
    

    为人类语言(英语,French等)指定Locale,用于翻译日/月的名称,以及定义文化规范,例如年,月和日期的顺序 . 请注意 Locale 与时区无关 .

    formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
    String output = zdt.format( formatter );
    

    本地化

    更好的是,让java.time自动完成本地化工作 .

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
    String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.
    

    关于java.time

    java.time框架内置于Java 8及更高版本中 . 这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat .

    Joda-Time项目现在位于maintenance mode,建议迁移到java.time类 .

    要了解更多信息,请参阅Oracle Tutorial . 并搜索Stack Overflow以获取许多示例和解释 . 规格是JSR 310 .

    您可以直接与数据库交换java.time对象 . 使用JDBC driver符合JDBC 4.2或更高版本 . 不需要字符串,不需要 java.sql.* 类 .

    从哪里获取java.time类?

    ThreeTen-Extra项目使用其他类扩展java.time . 该项目是未来可能添加到java.time的试验场 . 您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore .

  • 73
    Date todayDate = new Date();
    todayDate.getDay();
    todayDate.getHours();
    todayDate.getMinutes();
    todayDate.getMonth();
    todayDate.getTime();
    
  • 8

    要获得当前时间,您可以使用Java中的标准 System.currentTimeMillis() . 然后,您可以使用它来创建日期

    Date currentDate = new Date(System.currentTimeMillis());
    

    而正如别人所说,创造时间

    Time currentTime = new Time();
    currentTime.setToNow();
    
  • 5

    你可以(但不再应该 - 见下文!)使用android.text.format.Time

    Time now = new Time();
    now.setToNow();
    

    从上面链接的参考:

    Time类是java.util.Calendar和java.util.GregorianCalendar类的更快替代品 . Time类的实例表示以第二精度指定的时刻 .


    NOTE 1: 自从我写这个答案以来已经有好几年了,它是关于一个旧的,特定于Android的,现已弃用的类 . 谷歌现在says“他的 class 有很多问题,建议使用GregorianCalendar” .


    NOTE 2: 尽管 Time 类有一个 toMillis(ignoreDaylightSavings) 方法,但这只是方便传递给期望时间的方法(以毫秒为单位) . 时间值是 only precise to one second ;毫秒部分始终是 000 . 如果你在一个循环中

    Time time = new Time();   time.setToNow();
    Log.d("TIME TEST", Long.toString(time.toMillis(false)));
    ... do something that takes more than one millisecond, but less than one second ...
    

    结果序列将重复相同的值,例如 1410543204000 ,直到下一秒开始,此时 1410543205000 将开始重复 .

  • 11

    试试这个

    String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
    
  • 15

    我有一些API的答案问题,所以我融合了这些代码,我希望它能为他们服务:

    Time t = new Time(Time.getCurrentTimezone());
        t.setToNow();
        String date1 = t.format("%Y/%m/%d");
    
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
                Locale.ENGLISH);
        String var = dateFormat.format(date);
        String horafecha = var+ " - " + date1;
    
        tvTime.setText(horafecha);
    

    输出:03:25 PM - 2017/10/03

  • 1110

    下面的方法将返回字符串中的当前日期和时间,根据您的实际时区使用不同的时区 . 我使用过GMT

    public static String GetToday(){
        Date presentTime_Date = Calendar.getInstance().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.format(presentTime_Date);
    }
    

相关问题