我有一个代码来获取我的一个应用程序的年,月和日.
package com.cera.hyperionUtils;
import java.util.*;
public class HypDate {
public static int curdate(int field)
{
//1. Specify integer 1 for YEAR, 2 for MONTH, 5 DAY_OF_MONTH
Calendar c = new GregorianCalendar();
c.setLenient(true); //Allow overflow
//2. Extract and Return result
if (field == 2) {
field = c.get(Calendar.MONTH) + 1;
}
return c.get(field);
}
public static void main(String[] args)
{
System.out.println(HypDate.curdate(2));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我通过2它正在给0年和日打印正确.....我也试图使月份成为两位数.(像01一样)
有人可以帮帮我吗....?(我是java编码的新手)
您可能只想使用a SimpleDateFormat
来格式化它,而不是一个一个地返回这些.
假设我想要一个日期作为年 - 月 - 日:
// Necessary imports
import java.text.DateFormat;
import java.text.SimpleDateFormat;
// Declare class and stuff before this
public static String getFormattedDate() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(new Date());
}
public static void main(String[] args) {
System.out.println(getFormattedDate());
}
Run Code Online (Sandbox Code Playgroud)
输出 2010-10-29
编辑:
既然你只想要月份,你可以这样做:
public static String getFormattedMonth() {
DateFormat df = new SimpleDateFormat("MM");
return df.format(new Date());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8704 次 |
最近记录: |