java中SimpleDateFormat的一点技巧

将星期几的中文变成英文输出:

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Locale;
import java.text.SimpleDateFormat;

public class abc{
	public static void main(String[] args){
		GregorianCalendar gc = new GregorianCalendar();
		int today = gc.get(Calendar.DAY_OF_MONTH);
		int month = gc.get(Calendar.MONTH);
		gc.set(Calendar.DAY_OF_MONTH, 1);
		
		int weekday = gc.get(Calendar.DAY_OF_WEEK);
		
		int weekOfFirstDay = gc.getFirstDayOfWeek();
		
		int indent = 0;
		while(weekday != weekOfFirstDay){
			indent ++;
			gc.add(Calendar.DAY_OF_MONTH, -1);;
			weekday = gc.get(Calendar.DAY_OF_WEEK);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("F", Locale.US);
		String[] weekdayNames = sdf.getDateFormatSymbols().getShortWeekdays();
		
		do{
			System.out.printf("%4s", weekdayNames[weekday]);
			gc.add(Calendar.DAY_OF_MONTH, 1);
			weekday = gc.get(Calendar.DAY_OF_WEEK);
		}while(weekday != weekOfFirstDay);
		
		System.out.println();
	}
}
 输出如下:


Sun Mon Tue Wed Thu Fri Sat




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SimpleDateFormatJava的一个日期格式化类,它可以将日期格式化为指定的格式,并可以将字符串解析为日期对象。 以下是使用SimpleDateFormat格式日期的示例: ```java import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatExample { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(date); System.out.println("Formatted Date: " + formattedDate); } } ``` 输出结果为:Formatted Date: 2021-06-01 11:32:45 在上述示例,我们创建了一个SimpleDateFormat对象,并使用它将当前日期格式化为yyyy-MM-dd HH:mm:ss的格式。然后,我们将格式化后的日期字符串打印到控制台。 除了格式日期之外,SimpleDateFormat还可以解析日期字符串并将其转换为Date对象。以下是使用SimpleDateFormat解析日期字符串的示例: ```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatExample { public static void main(String[] args) { String dateString = "2021-06-01 11:32:45"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = formatter.parse(dateString); System.out.println("Parsed Date: " + date); } catch (ParseException e) { e.printStackTrace(); } } } ``` 输出结果为:Parsed Date: Tue Jun 01 11:32:45 CST 2021 在上述示例,我们创建了一个SimpleDateFormat对象,并使用它将日期字符串解析为Date对象。然后,我们将解析后的Date对象打印到控制台。请注意,我们必须在try-catch块处理ParseException异常,以防止解析失败。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我有健康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值