简体   繁体   English

如何使用日历将日期字符串转换为其他格式

[英]How to convert date strings to different format using Calendar

I am changing to Calendar from the deprecated Date library, I need to compare different time string objects. 我从过时的Date库更改为Calendar ,我需要比较不同的时间字符串对象。

How can I transform the time string (xx:xx:xx) to a full date (Tue Feb 03 21:02:25 CET 2015) using Calendar ? 如何使用Calendar将时间字符串(xx:xx:xx)转换为完整日期(Tue Feb 03 21:02:25 CET 2015)(Tue Feb 03 21:02:25 CET 2015)

I tried: 我试过了:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Test2 {

    public static void main(String[] args) throws ParseException {
        // Date date = new SimpleDateFormat("HH:mm:ss").parse("21:20:00"); // Date ist 1970!
        // System.out.println(date.toString());

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss | dd.MM.yy");
        cal.set(cal.YEAR, cal.MONTH, cal.DATE, 21, 20, 00);
        System.out.println(sdf2.format(cal.getTime()));

    }

}

and

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Test2 {

    public static void main(String[] args) throws ParseException {
        // Date date = new SimpleDateFormat("HH:mm:ss").parse("21:20:00"); // Date ist 1970!
        // System.out.println(date.toString());

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss | dd.MM.yy");
        cal.setTime(sdf.parse("21:20:00"));
        cal.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE);
        System.out.println(sdf2.format(cal.getTime()));

    }

}

But they return, respectively: 21:20:00 | 05.03.01 但是他们分别返回: 21:20:00 | 05.03.01 : 21:20:00 | 05.03.01 : 21:20:00 | 05.03.01 21:20:00 | 05.03.01

I want to be able to compare the result with other "full date objects" like Tue Feb 03 21:02:25 CET 2015 . 我希望能够将结果与其他“完整日期对象”进行比较,例如Tue Feb 03 21:02:25 CET 2015

Upated: 更新过的:

// Set the time in String
String stringDate = "04:10:13";
// Parse this time 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
// Set the parsed time to a Calendar object
cal.setTime(sdf.parse(stringDate));

Now you have to get the today's date and set the above time to it using Calendar#set method. 现在,您必须获取今天的日期,并使用Calendar#set方法设置上述时间。

// get today's time
Calendar today = Calendar.getInstance();
// print today date with current time,
System.out.println("Date before time is set: " + today.getTime());

// set today's hour to above time
today.set(Calendar.HOUR, cal.get(Calendar.HOUR));
// set today's minute to above time
today.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
// set today's seconds to above time
today.set(Calendar.SECOND, cal.get(Calendar.SECOND));
// print your new time
System.out.println("Date after time is set: " + today.getTime());

Output: 输出:

Date before time is set: Thu Feb 05 02:52:55 PKT 2015
Date after time is set: Thu Feb 05 04:10:13 PKT 2015

You can also set time in one line, 您还可以将时间设置为一行,

today.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH) , today.get(Calendar.DATE), cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));

Use JodaTime 使用JodaTime

Build a DateTime from current time 从当前时间建立一个DateTime

DateTime dt = new DateTime()
            .withMillisOfSecond(0)
            .withHourOfDay(21)
            .withMinuteOfHour(20)
            .withSecondOfMinute(0);

Build a DateTime from pattern 从模式构建DateTime

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(<YOUR_PATTERN>);
DateTime dt2 = dateTimeFormatter.parseDateTime(<YOUR_DATE_IN_A_STRING>);

Compare DateTimes 比较日期时间

if(dt.isAfter(dt2)){
    // DO ANYTHING
} else if(dt.isBefore(dt2){
    // DO WHATEVER
}

Get a Date from DateTime 从DateTime获取日期

Date date = dt.toDate()

LocalDateTime ( http://www.journaldev.com/2800/java-8-date-time-api-example-tutorial-localdate-instant-localdatetime-parse-and-format ) helped me here: LocalDateTime( http://www.journaldev.com/2800/java-8-date-time-api-example-tutorial-localdate-instant-localdatetime-parse-and-format )在这里帮助了我:

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Test {

    public static void main(String[] args) throws ParseException {
        String time = "14:12:01";
        String[] timePieces= time.split(":");
        int H = Integer.parseInt(timePieces[0]);
        int m = Integer.parseInt(timePieces[1]);
        int s = Integer.parseInt(timePieces[2]);

        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.of(H, m, s));
        System.out.println(today);

        LocalDateTime today2 = LocalDateTime.now().withHour(H).withMinute(m).withSecond(s).withNano(0);
        System.out.println(today2);
    }

}

To convert it to "Date" object: 要将其转换为“ Date”对象:

Date date = Date.from(today.atZone(ZoneId.systemDefault()).toInstant());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM