java中将Date日期格式转换为“yyyy-MM-dd HH:mm:ss”

本文详细介绍了如何使用Java的SimpleDateFormat类将当前日期时间Date对象转换为指定格式'yyyy-MM-dd HH:mm:ss',包括format()方法的运用和ParseException的处理。
该文章已生成可运行项目,

java中将Date日期格式转换为“yyyy-MM-dd HH:mm:ss”

方法:
format():date—>String;
parse():String—>date;

public static void main(String[] args) {
    Date currentTime = new Date();//当前日期
    System.out.println("当前日期默认格式:" + currentTime);
    //SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
    //SimpleDateFormat 使得可以选择任何用户定义的日期-时间格式的模式。
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义新的日期格式
    //format():将给定的 Date 格式化为日期/时间字符串。即:date--->String
    String dateString = formatter.format(currentTime);
    System.out.println("转换为String格式:" + dateString);
    try {
        Date date = formatter.parse(dateString);//parse():String--->date
        System.out.println("转化为date格式:" + date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

运行结果:
date

本文章已经生成可运行项目
P2911 [USACO08OCT] Bovine Bones G 是洛谷【入门 4】数组中的一道题目。题目描述为 Bessie 喜欢棋盘游戏和角色扮演游戏,她说服 Farmer John 带她去一家爱好商店,在那里她购买了三个骰子用于投掷,这些骰子分别有 S1、S2 和 S3 个面[^1]。 在解题代码方面,有 Java 和 C++ 两种实现。Java 代码通过定义一个长度为 81 的数组统计不同和值出现的次数,通过嵌套循环模拟掷骰子的过程,将每个和值对应的数组元素加 1,同时更新最大出现次数及其对应的和值,最后输出最大出现次数对应的和值[^2]。示例代码如下: ```java import java.util.Scanner; public class P2911_1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int s1 = sc.nextInt(), s2 = sc.nextInt(), s3 = sc.nextInt(); int[] arr = new int[81]; int max = 0; int temp = 0; for (int i = 1; i <= s1; i++) { for (int j = 1; j <= s2; j++) { for (int k = 1; k <= s3; k++) { arr[i + j + k]++; if (temp < arr[i + j + k]) { max = i + j + k; temp = arr[i + j + k]; } } } } System.out.println(max); sc.close(); } } ``` C++ 代码同样使用数组统计和值出现的次数,先通过三重循环模拟掷骰子得到所有可能的和值并更新对应次数,再遍历所有可能的和值范围,找出出现次数最多且和值最小的结果并输出[^3]。示例代码如下: ```cpp #include<bits/stdc++.h> using namespace std; int s1, s2, s3, res; int cnt[20000]; int maxn = -1e9; int main() { scanf("%d%d%d", &s1, &s2, &s3); for (int i = 1; i <= s1; ++i) { for (int j = 1; j <= s2; ++j) { for (int k = 1; k <= s3; ++k) { cnt[i + j + k]++; } } } for (int i = 3; i <= s1 + s2 + s3; ++i) { if (cnt[i] > maxn) maxn = cnt[i], res = i; } printf("%d", res); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值