Java 获取字符串的当前年份值
我需要获取字符串中的当前年份值,因此我做到了:Java 获取字符串的当前年份值,java,calendar,operating-system,date-format,Java,Calendar,Operating System,Date Format,我需要获取字符串中的当前年份值,因此我做到了: Calendar now = Calendar.getInstance(); DateFormat date = new SimpleDateFormat("yyyy"); String year = date.format(now); 它可以在ubuntu上运行,但不能在Windows7上运行 你知道为什么吗? 有没有更安全的方法 谢谢怎么样 Date currentDate = new Date(); String currentYear =
Calendar now = Calendar.getInstance();
DateFormat date = new SimpleDateFormat("yyyy");
String year = date.format(now);
它可以在ubuntu上运行,但不能在Windows7上运行
你知道为什么吗?
有没有更安全的方法
谢谢怎么样
Date currentDate = new Date();
String currentYear = String.valueOf(currentDate.getYear());
您可以使用以下方法从
日历
实例中简单获取年份:
试一试
您也可以这样做:
String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
时区
这个问题和公认的答案都忽略了时区的问题。在新年的时候,年份数会因时区的不同而有所不同
乔达时间
捆绑的java.util.Date和.Calendar类是出了名的麻烦。避开它们。在java 8中使用Joda Time或新的java.Time包
乔达时代的例子
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = DateTime.now( timeZone );
int year = dateTime.year().get();
Java 8:
java.time.Year.now();
以下是Java 8中的。有一个名为的集合,您可以轻松地从计算机时钟中获取当前年份 要将当前年份作为整数,您只需编写:
int thisYear = Year.now().getValue();
要将其作为字符串获取,请执行以下操作:
String thisYear = Year.now().toString();
在Java 8之前的Java版本中,还可以使用Java.sql.Date类。将年份转换为字符串和子字符串:
String currentYear = new java.sql.Date(System.currentTimeMillis()).toString().substring(0, 4);
Date#getYear()
已被弃用。另外,这是year-1900
。您可能应该解释一下。我使用这个。SimpleDataFormat使用日历。格式示例:“不工作”的确切含义是什么?这是一个低质量的答案。您没有描述这如何帮助解决问题,答案只是与原始OP几乎相同的代码,没有解释这如何解决问题。
int thisYear = Year.now().getValue();
String thisYear = Year.now().toString();
// enter code here
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy");
String year = format.format(date);
String currentYear = new java.sql.Date(System.currentTimeMillis()).toString().substring(0, 4);