Java--日期字符串使用

操作字符串日期等


1.字符串连接

public class Test {
    public static void main1(String[] args) {
        String str1 = "hello,";
        String str2 = "my name is Tom!";
        String str3 = str1 + str2;
        System.out.println(str3);
    }
    // 运行结果如下:
    // hello,my name is Tom!
    
    public static void main2(String[] args) {
        System.out.println(10 + 2.5 + "price"); 
        // 先进行算术运算,再进行字符串连接
        System.out.println("price" + 10 + 2.5);
        // 进行字符串连接
    }
    // 运行结果如下:
    // 12.5price
    // price102.5
}


2.字符串比较


        a.ava中String类提供了几种比较字符串的方法。最常用的是equals( )方法,它是比较两个字符串是否相等,返回boolean值。使用格式如下:str1.equals(str2);equals( )方法会比较两个字符串中的每个字符,相同的字母,如果大小写不同,其含义也是不同的。例如以下代码:

public class Test {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "HELLO";
        System.out.println(str1.equalsIgnoreCase(str2));
    }
    // 运行结果如下:
    // true
}


3.字符串截取


a.所谓的截取就是从某个字符串中截取该字符串中的一部分作为新的字符串。String类中提供substring方法来实现截取功能。使用格式如下:String substring (int beginIndex);或 String substring (int beginIndex, int endIndex); 字符串第一个字符的位置为0

public class Test {
    public static void main(String[] args) {
        String str1 = "I Love Java!";
        String subs1 = str1.substring(2);
        // 对字符串进行截取,从开始位置2截取
        String subs2 = str1.substring(2, 6);
        // 对字符串进行截取,截取 2-6 之间部分
    
        System.out.println("从开始位置 2 截取");
        System.out.println(subs1);
        System.out.println("从位置 2-6 截取");
        System.out.println(subs2);
    }
    // 运行结果如下:
    // 从开始位置 2 截取
    // Love Java
    // 从位置 2-6 截取
    // Love
}


4.字符串查找


a.字符串查找是指一个字符串中查找另一个字符串。String类中提供了 indexOf方法来实现查找功能。使用格式如下:
str.indexOf(string substr)或str.indexOf(string substr, fromIndex)
第一种是从指定字符串开始位置查找。第二种是从指定字符串并指定开始位置查找。简单来说就是获取下标(索引)例如:

public class Test {
    public static void main(String[] args) {
        String str1 = "I Love Java!";
        String str2 = "Love";
        int index1 = str1.indexOf(str2);
        // 从开始位置查找”Love“字符串
        int index2 = str1.indexOf(str2, 2);
        // 从索引 2 位置开始查找”Love“字符串
        System.out.println(index1);
        System.out.println(index2);
    }
    // 运行结果如下:
    // 2
    // 2
    // 这里特别说明一下如果查找没有或者不存在查找的字符串,返回的-1(我这里的编译器)
}


5.字符串与字符数组


a.有时会遇到字符串和字符数组相互转换的问题,可以方便地将字符数组转换为字符串,然后利用字符串对象的属性和方法,进一步对字符串进行处理。例如:

public class Test {
    public static void main(String[] args) {
        char[] helloArray = {'h','e','l','l','o'};
        // 将字符数组作为构造函数的参数
        String helloString = new String(helloArray);
        System.out.println(helloString);
    }
    // 运行结果如下:
    // hello
}


b.在使用new运算符创建字符串对象时,将字符串作为构造函数的参数,可以将字符数组转换为字符相应的字符串。相反,也可以将字符串转换为字符数组,这需要使用字符串对象的一个方法 toCharArray( )。它返回一个字符串对象转换过来的字符数组。例如

public class Test {
    public static void main(String[] args) {
        String helloString = "hello";
        char[] helloArray = helloString.toCharArray(); // 将字符串转换为字符数组
        for (int i = 0; i < helloArray.length; i++) {
            System.out.println(helloArray[i]);
        }
    }
    // 运行结果如下:
    // h
    // e
    // l
    // l 
    // o
}


6.获取今天日期


a.Java 8 中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。当你仅需要表示日期时就用这个类。

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期:"+today);
    }
}


7.分别获取年月日信息

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
 
        System.out.println("year:"+year);
        System.out.println("month:"+month);
        System.out.println("day:"+day);
 
    }
}


8.判断两个日期是否相等

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo04 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();
 
        LocalDate date2 = LocalDate.of(2018,2,5);
 
        if(date1.equals(date2)){
            System.out.println("时间相等");
        }else{
            System.out.println("时间不等");
        }
 
    }
}


9.检查像生日这种周期性时间

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.MonthDay;
 
public class Demo05 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();
 
        LocalDate date2 = LocalDate.of(2018,2,6);
        MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(date1);
 
        if(currentMonthDay.equals(birthday)){
            System.out.println("是你的生日");
        }else{
            System.out.println("你的生日还没有到");
        }
 
    }
}


10.获取当前时间


a.使用java.time获取

package com.shxt.demo02;
 
import java.time.LocalTime;
 
public class Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("获取当前的时间,不含有日期:"+time);
 
    }
}


b.通过Util包中的Date获取

       Date dates = new Date();        
       SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddHHmmss");
       System.out.println(dateFormat.format(dates));


c.通过Util包的Calendar 获取

    Calendar calendar= Calendar.getInstance(); 
    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    System.out.println(dateFormat.format(calendar.getTime()));


11.计算一周后的日期


a.LocalDate日期不包含时间信息,它的plus()方法用来增加天、周、月,ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型,返回后一定要用变量赋值。

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
public class Demo08 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期为:"+today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("一周后的日期为:"+nextWeek);
 
    }
}


12.计算一年前的日期和一年后的日期

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
public class Demo09 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
 
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("一年前的日期 : " + previousYear);
 
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("一年后的日期:"+nextYear);
 
    }
}


13.如何用Java判断日期是早于还是晚于另一个日期


a.另一个工作中常见的操作就是如何判断给定的一个日期是大于某天还是小于某天?在Java 8中,LocalDate类有两类方法isBefore()和isAfter()用于比较日期。调用isBefore()方法时,如果给定日期小于当前日期则返回true。

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
 
public class Demo11 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
 
        LocalDate tomorrow = LocalDate.of(2018,2,6);
        if(tomorrow.isAfter(today)){
            System.out.println("之后的日期:"+tomorrow);
        }
 
        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if(yesterday.isBefore(today)){
            System.out.println("之前的日期:"+yesterday);
        }
    }
}


14.如何在Java 8中检查闰年

package com.shxt.demo02;
 
import java.time.LocalDate;
 
public class Demo14 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        if(today.isLeapYear()){
            System.out.println("This year is Leap year");
        }else {
            System.out.println("2018 is not a Leap year");
        }
 
    }
}


15.在Java 8中获取当前的时间戳


a.Instant类有一个静态工厂方法now()会返回当前的时间戳,如下所示:

package com.shxt.demo02;
 
import java.time.Instant;
 
public class Demo16 {
    public static void main(String[] args) {
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp.toEpochMilli());
    }
}


16.字符串互转日期类型

package com.shxt.demo02;
 
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
public class Demo18 {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();
 
        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //日期转字符串
        String str = date.format(format1);
 
        System.out.println("日期转换为字符串:"+str);
 
        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //字符串转日期
        LocalDate date2 = LocalDate.parse(str,format2);
        System.out.println("日期类型:"+date2);
 
    }
}


17.生成随机数

import java.util.Date;
  
public class DateDemo {
   public static void main(String args[]) {
       
    int uusid = (int)(Math.random()*100+1);
       
       System.out.println(uusid);
   }
}

18.生成6位数随机字母数字

public class test
{

    public static void main(String[] args)
    {    
        //用字符数组的方式随机
        String randomcode2 = "";
        String model = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        char[] m = model.toCharArray();
        
        for (int j=0;j<6 ;j++ )
        {
            char c = m[(int)(Math.random()*model.length())];
            randomcode2 = randomcode2 + c;
        }
        
        System.out.println(randomcode2);
     
    }


1.equals()和==的区别


- “==” :判断两个对象的地址是不是相等。即判断两个对象是不是同一个对象。
- equals():判断两个对象的内容是否相等。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值