Java 获取网络时间,并根据网络时间获取这个月的月初时间

获取网络时间,并根据网络当前时间获取这个月的月初时间,然后转换为String类型

1. 获取网络时间(可直接用,无需修改)

    public class DateUtils()  {
    
       /**
     * 获取网络时间
     * @return
     */
       public static Date getWebsiteDatetime(){
        try {
            URL url = new URL("http://www.baidu.com");// 取得资源对象
            URLConnection uc = url.openConnection();// 生成连接对象
            uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
            Date date = new Date(ld);// 转换为标准时间对象
            return date;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    }
2.根据查询出来的时间查询本月初的时间

//获取查询出来的网络时间
//我把getWebsiteDatetime() 方法封装到了DateUtils类中,直接调用
Date newTime = DateUtils.getWebsiteDatetime();
//获取本月初时间
Date firstTime = new Date(newTime.getYear(),newTime.getMonth(),01);

3.date类型转换为String类型

SimpleDateFormat dataformatter = new SimpleDateFormat( "yyyy-MM-dd");
//将当前网络时间转换为String类型
String format = dataformatter.format(newTime);
//将月初时间转换为String类型
String format1 = dataformatter.format(firstTime);

4. 测试运行
    @Test
    public  void main()  {


        SimpleDateFormat dataformatter = new SimpleDateFormat( "yyyy-MM-dd");
        //获取当前时间
        //我把getWebsiteDatetime() 方法封装到了DateUtils类中,直接调用
        Date newTime = DateUtils.getWebsiteDatetime();
        //获取本月 月初时间
        Date firstTime = new Date(newTime.getYear(),newTime.getMonth(),01);
        //转换为String类型
        String format = dataformatter.format(newTime);
        String format1 = dataformatter.format(firstTime);
        System.out.println("获取的当前时间为:"+format);
        System.out.println("获取的本月月初时间为:"+format1);
   }
5. 运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值