简体   繁体   English

Java字符串到日期的转换格式不同

[英]Java String to Date Conversion in different format

So i have String trDate="20120106"; 所以我有String trDate="20120106"; and want to get Date trDate=2012-01-06 and am trying to use SimpleDateFormat for changing the pattern but first i get to parse the string and then generate date and then try to call format which gives me back string but i need date, any suggestions, here is the code i have: 并想获取Date trDate=2012-01-06并尝试使用SimpleDateFormat更改模式,但首先我要parse字符串,然后生成日期,然后尝试调用给我返回字符串的format ,但我需要日期,任何建议,这是我的代码:

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).format(tradeDate);
Date krwTradeDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).parse(krwtrDate);

Here is similar question but it does not answer my question 这是类似的问题,但不能回答我的问题

I need converted string in Date format only because i need to pass it to another function that expects Date object only. 我只需要将转换后的字符串转换为Date format因为我需要将其传递给仅需要Date object另一个函数。

Would really appreciate if someone can give example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format? 如果有人可以举一个如何从yyyymmdd格式的string获取yyyy-mm-dd格式的date示例,我们将不胜感激?

--- Answer updated due to commentary --- ---答案因评论而更新---

Ok, so the API you are using demands a String, which represents a Date in the format of 2012-04-20 好的,因此您使用的API需要一个字符串,该字符串代表格式为2012-04-20的日期

You then need to parse the incorrectly formatted Date and then format it again in the needed format. 然后,您需要解析格式错误的Date ,然后以所需的格式将其再次格式化。

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(tradeDate);

Also note that I changed your "month" designator, as you have made a very common mistake of using m for month. 还要注意,我更改了您的“月”代号,因为您犯了一个非常普遍的错误,即将m用作月。 Due to the "hours:minutes:seconds" date formats have two common "names" that both start with m , minutes and months. 由于使用“ hours:minutes:seconds”,日期格式具有两个常见的“名称”,均以m ,分钟和月开头。 Uppercase M is therefore used for months, while lowercase m is used for minutes. 因此,大写M使用几个月,而小写m使用几分钟。 I'll bet that this is the real reason you're encountering problems. 我敢打赌,这是您遇到问题的真正原因。

--- Original post follows --- ---原始帖子如下---

If your APIneeds a java.util.Date , then you don't need to do as much as you have. 如果您的API需要一个java.util.Date ,那么您不需要做太多的事情。 You actually have the java.util.Date with just the two lines 您实际上只有两行就有java.util.Date

String trDate="20120106";    
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);

But this solution might not make sense without a quick review of what java.util.Date s are. 但是,如果不快速回顾一下java.util.Date是什么,那么该解决方案可能就没有意义。 Dates are things, but how they are presented is divorced from what they are. Dates是事物,但是它们的呈现方式与它们的本质不同。

At any moment in time, there is one Date instance that describes that moment in time. 在任何时候,都有一个Date实例描述该时刻。 How that Date instance should be presented is not in agreement, it depends heavily on what language the viewer speaks, which country they are in, what rules the country has imposed (daylight savings time), and what their cultural background has done before. Date实例的显示方式并不一致,这在很大程度上取决于观众说什么语言,他们所在的国家/地区,该国家/地区制定的规则(夏令时)以及他们以前的文化背景。

As such, a Date has no single associated presentation. 因此, Date没有单个关联的演示文稿。 That's why every "get the X" method on Date is deprecated (where X is day, month, hour, year, etc.), with the exception of grabbing the milliseconds from the 0 date (known as the epoch). 这就是为什么不赞成使用Date上的每个“获取X”方法(其中X为日,月,时,年等)的原因,除了从0日期开始获取毫秒数(称为历元)。

So, for every Date that is to be properly presented, you need to convert it to a String using rules that are specific to the language, country, time zone, and cultural precedent. 因此,对于要正确显示的每个Date ,您需要使用特定于语言,国家/地区,时区和文化先例的规则将其转换为String The object that understands these rules and applies them is the DateFormat . 理解这些规则并应用它们的对象是DateFormat

Which means, once you get the Date you don't need to reformat it and re-parse it to get the "right" Date as the two dates should be the same (for the same locale). 这意味着,一旦获得Date ,就不需要重新格式化它并重新解析它以获得“正确的” Date因为两个日期应该是相同的(对于相同的语言环境)。

can you give me an example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format 你能给我一个例子,如何从yyyymmdd格式的字符串中获取yyyy-mm-dd格式的日期

A Date objects does not have a format associated with it. Date对象没有与之关联的格式。 Internally it typically just stores a long value. 在内部,它通常只存储一个long值。

If some other methods is responsible for printing the date, then you unfortunately have no control over how the resulting output is formatted. 如果使用其他方法来打印日期,那么很遗憾,您无法控制结果输出的格式。

Do I understand it well? 我听得懂吗?

You have a method which only accepts Date as parameter, and internally that method converts the Date to a string in the wrong format using toString()? 您有一个仅接受Date作为参数的方法,并且该方法在内部使用toString()将Date转换为格式错误的字符串?

Best is to modify that method and exchange the use of toString() with SimpleDateFormat.format(). 最好是修改该方法,并将toString()与SimpleDateFormat.format()交换。

If you can't modify that method, than you can "cheat" with OO, ie replace the toString method with your own implementation, for example like this: 如果您不能修改该方法,则可以用OO“欺骗”,即用您自己的实现替换toString方法,例如:

public class MyDate {
   private static final FMT = SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);

   MyDate(long time) {
      super(time);
   }

   String toString() {
      return FMT.format(this);
   }
}

and you call your method with 然后用

xxx = myMethod(new MyDate(new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate).getTime()));

But if that method does not use toString internally but SimpleDateFormat with the wrong format, then my proposition does not work. 但是,如果该方法未在内部使用toString,而在SimpleDateFormat中使用了错误的格式,则我的主张不起作用。

If the String date always comes in the format you have mentioned than you can use the subString method to extract the year, month and day. 如果字符串日期总是采用您提到的格式,则可以使用subString方法提取年,月和日。

String trDate="20120106"; 字符串trDate =“ 20120106”;

Using the subString method for String extract the Year, month and day 对字符串使用subString方法提取年,月和日

String year = "2012"; 字符串年份=“ 2012”;
String month = "01"; 字符串月份=“ 01”;
String day = "06"; 字符串日=“ 06”;

And parse these to integer. 并将其解析为整数。 Assuming you will do the parsing of string to integer 假设您将字符串解析为整数

int intYear = 2012; int intYear = 2012;
int intMonth = 01; int intMonth = 01;
int intDay = 06; int intDay = 06;

Calendar calendar= new GregorianCalendar(intYear, intMonth - 1, intDay); Calendar calendar = new GregorianCalendar(intYear,intMonth-1,intDay);

Date date = new Date(calendar); 日期日期=新日期(日历);

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

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