search
HomeJavajavaTutorialHow to use Stringbuild, Date and Calendar classes in Java

Stringbuild class

Since the object content of the String class cannot be changed, a new String object will be constructed every time it is spliced, which is time-consuming and a waste of memory space

At this time, you need to use java The provided StringBuild class solves this problem

StringBuilder is also called a variable character sequence. It is a string buffer similar to String and can be regarded as a container. Many strings can be held in the container

Variable means that the content in the StringBuilder object is variable

Construction method

public StringBuilder(): Create an empty buffer

public StringBuilder(String srt): Create a buffer that stores str

//public StringBuilder():创建一个空白可变字符串对象,不含有任何内容
StringBuilder sb = new StringBuilder();
System.out.println("sb:" + sb);
System.out.println("sb.length():" + sb.length());

//public StringBuilder(String str):根据字符串的内容,来创建可变字符串对象
StringBuilder sb2 = new StringBuilder("hello");
System.out.println("sb2:" + sb2);
System.out.println("sb2.length():" + sb2.length());

append

public StringBuilder append(Object obj) : Append any type of data to the container and convert it to a string

// 链式编程, 链式编程返回结果 看最后调用的方法
StringBuilder abc = new StringBuilder(stringBuilder.append(10).append("abc").append(10.1).append(new Object()).toString());
System.out.println("abc = " + abc);

reverse

public StringBuilding reverse(): Reverse the buffer data

String string = new StringBuilder(abc).reverse().toString();
System.out.println(string);

Date class

java.util.Date Represents a specific moment, accurate to milliseconds

Construction method

public Date(): The current date object, the millisecond value elapsed from the time when the program is run to the time origin, is converted into a Date object, allocates a Date object and initializes this object to represent the time at which it is allocated (accurate to milliseconds).

public Date(long date): Convert the millisecond value date of the specified parameter into a Date object, allocate the Date object and initialize this object

Time origin : January 1, 1970 00:00:00
China is in the East 8th District. Strictly speaking, it is January 1, 1970 00:08:00
1s = 1000ms

public static void main(String[] args) {
	// 创建日期对象,把当前的时间
	System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2020
	// 创建日期对象,把当前的毫秒值转成日期对象
	System.out.println(new Date(0)); // Thu Jan 01 08:00:00 CST 1970
}

getTime

long getTime(): Get the millisecond value of the date object

// 获取从 时间原点 到 当前日期 的毫秒值
long time = nowTime.getTime();
System.out.println(time);

setTime

void setTime(long time): Set millisecond value

 // 设置偏移毫秒值为0, 即时间原点
nowTime.setTime(0);
System.out.println(nowTime);

DateFormat

java.text.DateFormat is an abstract class of date/time formatting subclass, we can use this class to help us complete it Conversion between date and text, that is, you can convert back and forth between Date object and String object.

SimpleDateFormat

Since DateFormat is an abstract class and cannot be used directly, a commonly used subclass java.text.SimpleDateFormat is required.
This class requires a pattern (format) to specify the standard for formatting or parsing.

Construction method

public SimpleDateFormat(): Constructs SimpleDateFormat using the default mode and locale date format symbols.

The default format is: (year)-(month)-(day) (am/pm)xx:xx

public SimpleDateFormat(String pattern) : Constructs a SimpleDateFormat with the given pattern and date format symbols of the default locale.

The parameter pattern is a string representing a custom format for date and time.

Commonly used format rules are:

Identifier letters (case sensitive) Meaning
y
M
d
H hours
m minutes
s Seconds

Note: For more detailed format rules, please refer to the API documentation of the SimpleDateFormat class.

Convert date object to string

public String format(Date date): Pass the date object and return the formatted string.

// 将当前日期 转换为 x年x月x日 xx:xx:xx
Date nowTime = new Date();
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss E");
System.out.println(df.format(nowTime));

Convert string to date object

public Date parse(String source) Pass the string and return the date object

// 获取sDate所代表的时间的毫秒值
String sDate = "1949-10-01";
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
// parse 若无法解析字符串会抛出异常 ParseException
Date date = df2.parse(sDate);
long time = date.getTime();
System.out.println(time);

Calendar class

java.util.Calendar Calendar calendar class, replaces many Date methods

It is an abstract class, but provides static methods to create objects, and also provides Many static attributes

Month 0-11 represents January-December
The first day of the week abroad is Sunday

getInstance

public static Calendar getInstance(): Get a calendar using the default time zone and locale.

Calendar c = Calendar.getInstance();
System.out.println(c);

Static attributes and their corresponding fields

Use class name.property name to call, representing the given calendar field:

##DAY_OF_WEEKWeek Day in (day of the week, Sunday is 1, you can use -1)

get

int get(int field): 返回给定日历字段的值

int year = c.get(Calendar.YEAR);
// 0-11表示月份 需要+1
int month = c.get(Calendar.MONTH) + 1;
// DATE 和 DAY_OF_MONTH 的值是一样的
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"年"+month+"月"+day+"日");

getTimeZone

TimeZone getTimeZone() 获取时区

TimeZone timeZone = c.getTimeZone();
System.out.println(timeZone);

add

void add(int field, int amount): 根据日历规则 为给定的字段添加或减去指定的时间量

// 将日历设置为2000.5.1, 当前时间为2023.4.5
// add方法设置偏移量
c.add(Calendar.YEAR, -23);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DATE, -4);
System.out.println(c.get(Calendar.YEAR)+"."+(c.get(Calendar.MONTH) + 1)+"."+c.get(Calendar.DAY_OF_MONTH));

set

void set(int field, int value): 将给定的日历字段设置为给定值

void set(int year, int month, int date) 直接设置年月日为指定值

// set(int field, int value)方法 将日历设置为2001.4.2
c.set(Calendar.YEAR, 2001);
c.set(Calendar.MONTH, 3);
c.set(Calendar.DAY_OF_MONTH, 2);
System.out.println(c.get(Calendar.YEAR)+"."+(c.get(Calendar.MONTH) + 1)+"."+c.get(Calendar.DAY_OF_MONTH));

// set(int year, int month, int date)方法 将日历设置为2003.10.1
c.set(2003, 9, 1);
System.out.println(c.get(Calendar.YEAR)+"."+(c.get(Calendar.MONTH) + 1)+"."+c.get(Calendar.DAY_OF_MONTH));

getTime

Date getTime(): 将日历对象转为日期对象

Date date = c.getTime();
System.out.println(date);

练习

定义一个方法, 使用StringBuild将数组转换为 [元素1,元素2...] 的格式

public class Demo {
    public static void main(String[] args) {
        int[] arr = {3,765,8234,1,23};
        System.out.println(arrayConcatToSting(arr));
    }

    public static String arrayConcatToSting(int[] arr) {
        StringBuilder stringBuilder1 = new StringBuilder("[");
        for (int i = 0; i < arr.length; i++) {
            stringBuilder1.append(arr[i]);
            if (i < arr.length - 1) {
                stringBuilder1.append(", ");
            } else if (i == arr.length - 1){
                stringBuilder1.append("]");
            }
        }
        return stringBuilder1.toString();
    }

}

计算一个人活了多少天

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Demo {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入您的生日(年.月.日): ");
        System.out.println("您活了"+howLongHaveYouLived(sc.nextLine())+"天");
    }

    public static long howLongHaveYouLived (String str) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
        Date birthDay = df.parse(str);
        long birthDayTime = birthDay.getTime();
        long nowTime = new Date().getTime();
        return (nowTime - birthDayTime) / 1000 / 60 / 60 /24;
    }
}

计算指定年份的2月有多少天

import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        // 计算指定年份的2月有多少天
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入您要指定的年份: ");
        int inputYear = sc.nextInt();
        System.out.println(inputYear+"年的2月有"+getDay(inputYear)+"天");
    }

    public static int getDay(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, 2, 1);
        calendar.add(Calendar.DATE, -1);
        return calendar.get(Calendar.DATE);
    }
}
Field value Meaning
YEAR
MONTH Month (starts from 0, can be used as 1)
DAY_OF_MONTH Day of the month (number)
HOUR hour (12-hour format)
HOUR_OF_DAY hour (24-hour format)
MINUTE Minutes
SECOND Seconds

The above is the detailed content of How to use Stringbuild, Date and Calendar classes in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),