java SimpleDateFormat

java SimpleDateFormat

作用:

  • 可以对Date对象或时间毫秒值格式化成我们想要的时间形式
  • 也可以把字符串形式解析成日期对象
//格式化
Date对象 ========20991111111111
    
时间毫秒值========20991111111111

    
解析:20991111111111  ========Date对象

在这里插入图片描述

使用实例:

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatDemo {
    public static void main(String[] args) {
        //1.日期
        Date date = new Date();
        //2.简单日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(date));

        System.out.println("----------格式化时间毫秒值---------");
        System.out.println(sdf.format(date.getTime()));

        System.out.println("---------解析时间---------");

    }
}

在这里插入图片描述

使用案例:

package com.itheima.d1_simpledateformate;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 案例:秒杀活动
 * 秒杀开始时间:2020年11月11日 0:0:0
 * 秒杀结束时间:2020年11月11日 0:10:0
 *
 * 需求:小贾下单并付款时间:2020年11月11日 0:03:47
 *      小皮下单并付款时间:2022年11月11日 0:10:11
 *      用代码说明这两位同学有没有参加上秒杀活动?
 * */

public class SimpleDateFormatDemo2 {
    public static void main(String[] args) throws ParseException {
        //1.简单时间格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:MM:ss");
        //2.时间字符串
        String strStartDate = "2020年11月11日 0:0:0";
        String strEndDate = "2020年11月11日 0:10:0";
        String strDate1 = "2020年11月11日 0:03:47";
        String strDate2 = "2020年11月11日 0:10:11";
        //3.活动开始和结束的时间毫秒值
        long startTime = sdf.parse(strStartDate).getTime();
        long endtTime = sdf.parse(strEndDate).getTime();
        long time1 = sdf.parse(strDate1).getTime();
        long time2 = sdf.parse(strDate2).getTime();

        if (time1>=startTime && time1<= endtTime){
            System.out.println("小贾参加了秒杀活动!");
        }else{
            System.out.println("小贾秒杀失败,很遗憾未参加活动~~~~~~");
        }

        if (time2>=startTime && time2<= endtTime){
            System.out.println("小皮参加了秒杀活动!");
        }else{
            System.out.println("小皮秒杀失败,很遗憾未参加活动~~~~~~");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值