如何从Date获取当前月份

时间:2014-08-01 06:41:11

标签: java android date calendar simpledateformat

我需要将长值转换为任何日期。接下来我希望写出月份,转换为String。我想在TextView上显示月份。

我试过了:

Date dt = new Date();
Calendar cal= Calendar.getInstance();
cal.setTime(dt);  //get current time

long dateAsLong = calendar.getTimeInMillis(); // get currentTime as long

CalendarView.setDate(dateAsLong); // give the view CalendarView the current date 


TextView tv= (TextView) findViewById(R.id.TextViewDate);
tv.setText(String.valueOf(dateAsLong)); // <-- but this is wrong

4 个答案:

答案 0 :(得分:2)

TL;博士

  

将长值转换为...日期...写出的月份

Instant.ofEpochMilli( myMillis )
       .atZone( ZoneId.of( "Pacfic/Auckland" ) ) 
       .getMonth()
       .getDisplayName( TextStyle.FULL , Locale.ITALY )  // Or Locale.US, Locale.UK, etc.
  

ottobre

避免遗留日期时间类

其他Answers使用现在遗留下来的麻烦的旧日期时间类,取而代之的是java.time类。

java.time

假设您的long值表示自UTC 1970年第一个时刻以来的毫秒数,请使用Instant

Instant类代表UTC中时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。

Instant instant = Instant.ofEpochMilli( myMillis ) ;

你想写一个月。确定一个月意味着确定一个日期。确定日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "Africa/Tunis" ); 
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment in history, but adjusted into the wall-clock time of a particular region of people.

现在审问这个月。 java.time类包含Month枚举,用于表示1月至12月的月份。

Month m = zdt.getMonth() ;

Month枚举包括方便的方法,例如以自动本地化格式生成字符串。

String output = m.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH )  ;  // Or Locale.US, Locale.ITALY, etc.

关于java.time

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

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

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

答案 1 :(得分:1)

使用以下代码:

    long longDate=12334;
    Date date=new Date(longDate);
    String month=new SimpleDateFormat("MMMM").format(date); //you can use month for display

希望它有所帮助。

答案 2 :(得分:1)

    Date date = new Date();
    System.out.println(date.getTime());//Timestamp 
    long timestamp = date.getTime();
    date = new Date(timestamp);
    String month = new SimpleDateFormat("MMMM").format(date);//Get month string
    System.out.println(month);

答案 3 :(得分:1)

首先从Long

获取日期
long val = 1346524199000l;
Date date=new Date(val);
SimpleDateFormat df2 = new SimpleDateFormat("MMM");
String month= df2.format(date);

一旦你有一个字符串形式的月份,使用下面的代码

将其转换为android textView
textview.setText(month);
相关问题