简体   繁体   English

将字符串转换为日期并将日期转换回字符串

[英]converting string to date and converting date back to string

Hi for some of the requirement i need to convert the string representation of date(with no format) to date object and convert back to string(with a specific format) 您好,对于某些要求,我需要将日期(无格式)的字符串表示形式转换为日期对象,然后转换回字符串(具有特定格式)

This is what i tried so far, the output is not coming as expected and it's printing something like 08140009 - Any idea what is this 这是我到目前为止尝试过的结果,输出未达到预期的效果,并且正在打印08140009之类的东西-知道这是什么

And please provide any suggestions. 并请提供任何建议。

MY code is : 我的代码是:

public String getDateBackToCST(String  createDate){

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MMddyyyy");
    TimeZone obj = TimeZone.getTimeZone("CST");
    dateFormatter.setTimeZone(obj);
    Date createdDate = null;

    try {
        createdDate = dateFormatter.parse(createDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateFormatter.format(createdDate);
}

You need to specific proper flags for SimpleDateFormat. 您需要为SimpleDateFormat设置适当的标志。 You have 2 options to specify timezone z and Z and to specify day name use E like this 您有2个选项来指定时区zZ并使用E来指定日期名称,像这样

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main {



    public static void main(String[] args) throws ParseException {

        String date = "Sat Sep 20 23:39:04 IST 2014 ";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
        System.out.println(sdf.parse(date));

    }
}

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

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