如何将当前时间的正常日期转换为日期

时间:2014-06-12 15:52:37

标签: java date datetime

我遇到以下问题,我有一个约会dd-mm-yyyy,我需要将其转换为yyyy-MM-dd HH:mm(即使用给定日期和当前小时和分钟)。

示例: 鉴于日期:11-06-2014,我应该2014-06-11 09:30

 public String previousDateString(String dateString)
        throws ParseException {
    // Create a date formatter using your format string
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    // Parse the given date string into a Date object.
    // Note: This can throw a ParseException.
    Date myDate = dateFormat.parse(dateString);

    // Use the Calendar class to subtract one day
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(myDate);
    calendar.setTime(myDate);
    calendar.add(Calendar.DAY_OF_YEAR, -1);

    // Use the date formatter to produce a formatted date string
    Date previousDate = calendar.getTime();
    String result = dateFormat.format(previousDate);

    return result;
}   

我已尝试过此代码,但我收到了2014-06-10 00:00

3 个答案:

答案 0 :(得分:0)

您获得00:00,因为您在11-06-2014中传递的信息不包含小时或分钟。

如果您想要转换时间内的小时:分钟,则需要在输入中添加更多信息或获取当前小时/分钟。

答案 1 :(得分:0)

您必须使用两个Calendar实例,因为Calendar setTime方法将小时和分钟设置为零。

package com.ggl.testing;

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

public class FormatDate {

    private static final DateFormat inputDateFormat =
            new SimpleDateFormat("dd-MM-yyyy");
    private static final DateFormat outputDateFormat = 
            new SimpleDateFormat("yyyy-MM-dd HH:mm");

    private Calendar calendar;

    public String previousDateString(String dateString) 
            throws ParseException {
        Calendar now = Calendar.getInstance();

        calendar = Calendar.getInstance();
        Date myDate = inputDateFormat.parse(dateString);
        calendar.setTime(myDate);
        calendar.set(Calendar.HOUR_OF_DAY, 
                now.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, 
                now.get(Calendar.MINUTE));

        return outputDateFormat.format(calendar.getTime());
    }

    public static void main(String[] args) {
        String dateString = "10-06-2014";
        try {
            String output = 
                    new FormatDate().previousDateString(dateString);
            System.out.println(output);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

输出 - 2014-06-10 10:47

答案 2 :(得分:0)

如果您可以选择使用Java 8,则可以编写如下解决方案:

private LocalTime startOfDay = LocalTime.of(9, 30);

public String previousDateString(String dateString) {
    LocalDate yesterday = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDateTime yesterdayTime = LocalDateTime.of(yesterday, startOfDay);
    return yesterdayTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}