This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 9 years ago.
I am getting an epoch String from my DB which looks something like this : 1391328000000
I am having a hard time trying to convert it to Java Date.
I tried the following :
private String buildDate(String dateString){
System.out.println("dateString " + dateString);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(Integer.parseInt(dateString));
return formatted;
}
I think you're overthinking about the DateFormat. If I want to simply obtain a Date instance, what I would try is the following:
Date d = new Date(Long.parseLong(dateString));
You need to turn it into a java.util.Date object in order for SimpleDateFormat to handle it. Also, a value like what you quoted needs to be parsed as a long, as it is too large for an int.
That is, change the line where you set formatted to be:
String formatted = format.format(new Date(Long.parseLong(dateString)));
As an aside, if the project you're working on can handle an extra external dependency, switch date/time handling over to the joda library. The stuff in java.util (that is, Date and Calendar) rapidly becomes painful and error-prone to work with.
Related
This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 5 years ago.
I am trying to change the format of Date objects, I am trying to do it in this way:
for(Date date : dates){
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String formatterDate = formatter.format(date);
Date d = formatter.parse(formatter.format(date));
}
But this does not have any effect on the d object, it is still with the old format, can't really understand why it is like that.
Please try to keep two concepts apart: your data and the presentation of the data to your user (or formatting for other purposes like inclusion in JSON). An int holding the value 7 can be presented as (formatted into) 7, 07, 007 or +7 while still just holding the same value without any formatting information — the formatting lies outside the int. Just the same, a Date holds a point in time, it can be presented as (formatted into) “June 1st 2017, 12:46:01.169”, “2017/06/01” or “1 Jun 2017” while still just holding the same value without any formatting information — the formatting lies outside the Date.
Depending on your requirements, one option is you store your date as a Date (or better, an instance of one of the modern date and time classes like LocalDate) and keep a formatter around so you can format it every time you need to show it to the user. If this won’t work and you need to store the date in a specific format, then store it as a String.
Java 8 (7, 6) date and time API
Now I have been ranting about using the newer Java date and time classes in the comments, so it might be unfair not to show you that they work. The question tries to format as yyyy-MM-dd, which we may do with the following piece of code.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd");
for (LocalDate date : localDates) {
String formatterDate = date.format(dateFormatter);
System.out.println(formatterDate);
}
In one run I got
2017/05/23
2017/06/01
Should your objects in the list have other types than LocalDate, most other newer date and time types can be formatted in exactly the same way using the same DateTimeFormatter. Instant is a little special in this respect because it doesn’t contain a date, but you may do for example myInstant.atZone(ZoneId.of("Europe/Oslo")).format(dateFormatter) to obtain the date it was/will be in Oslo’s time zone at that instant.
The modern classes were introduced in Java 8 and are enhanced a bit in Java 9. They have been backported to Java 6 and 7 in the ThreeTen Backport with a special edition for Android, ThreeTenABP. So I really see no reason why you should not prefer to use them in your own code.
Try this one.
String formattedDate = null;
SimpleDateFormat sdf = new SimpleDateFormat(format you want);
formattedDate = sdf.format( the date you want to format );
return formattedDate;
some not best solution, but it works: this method will convert Date object to String of any pattern you need
public static void format(Date date){
String pattern = "MMM d yyyy";
LocalDateTime localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String result = formatter.format(localDate);
// new Date() -> Jun 1 2017
}
SimpleDateFormat is useful while converting Date to String or vice-versa. java.util.Date format will always remain same. If you want to display it in standalone application then use date.getxxx() methods and choose your design.
This question already has answers here:
Convert String to java.util.Date
(4 answers)
Closed 7 years ago.
I read more questions on the web but I dont' find a solution yet.
I have a String like "14/05/1994", exactly in this format.
I need to covert it into java.util.Date in the same format.
I tried:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date dataFrom = new Date();
dataFrom = df.format("14/05/1994");
But the result is: Sat May 14 00:00:00 CET 1994
It's possibile have as a result: 14/05/1994 not as a String, but as java.util.Date?
A java.util.Date doesn't have a format. It's just a date.
When you print it out, e.g. using toString(), it uses a default format, which is what you're seeing. But you have that date.
Date dataFrom = new Date();
dataFrom = df.format("14/05/1994");
I don't think that can be your code because DateFormat.format accepts a Date and returns a String, not the other way around. You might mean df.parse, which would get you the results you describe. But if you take your SimpleDateFormat and use its format method on the Date, then you should get back out 14/05/1994 as you want. A java.util.Date doesn't have a format, though.
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 7 years ago.
I have this weird date format that I have to parse.
2015-12-18T03:36:06.000+0000
I am currently mapping a regex to date formats so I can parse different dates. However, this format got me confused. Any help appreciated.
To parse a String into a Date in Java, you use a DateFormat object, and specify the format the date is in. There is no need to use a Regex, the Java library has a way to do this for you.
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
final Date d = df.parse("2015-12-18T03:36:06.000+0000"); // From your code above
System.out.println(d);
See the JavaDoc for SimpleDateFormat for more explanation as to what the symbols mean. This is actually a common format for dates called ISO 8601, I just took the pattern right from the documentation.
Watch out! These DateFormat objects are not threadsafe.
This question already has answers here:
java.text.ParseException: Unparseable date
(10 answers)
Closed 8 years ago.
I am trying to convert a String ("01-OCT-2014") into Date format.
Below is my code for this.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date d= formatter.parse("01-OCT-2014");
System.out.println("Converted date:"+d);
The above code is working fine in Windows.
But when I am running in Unix environment, it is throwing an exception Unparseable date
Can any one help me out in solving this issue..
I suspect the problem is simply that your Unix environment isn't running in an English locale - so when it tries to parse the month name, it's not recognizing "OCT" as a valid value.
I would suggest using code like this:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Date d = formatter.parse("01-OCT-2014");
System.out.println("Converted date: " + d);
You might also want to specify the time zone of the formatter - if you're just parsing a date, then using UTC would make sense. Note that your output will use the system local time zone, because you're using Date.toString() - that doesn't mean that the Date has any notion of the time zone in its data; a Date is just a point in time.
This question already has answers here:
Parse any date in Java
(6 answers)
Recognise an arbitrary date string [closed]
(15 answers)
Closed 8 years ago.
I need to check the string against all possible dateFormats and need to check its valid date or not.
The problem I am facing is I can't predict the date format as its getting from some other web sources. One example is September 21 2012 1255 PM ET, .But the format may vary.
I suggest that you implement your own Parse method and use regular expressions to determine how the string should be parsed. You should not expect to parse a date with any format without knowing which it is.
Personally I would implement something like this (but then again, I haven´t coded Java in quite some time):
public SimpleDateFormat ParseDate(string s)
{
SimpleDateFormat parsedDate;
if(s.matches("0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d"))
parsedDate = new SimpleDateFormat("MM/dd/yyyy");
else if(s.matches([PATTERN2]))
parsedDate = new SimpleDateFormat([DATE PATTERN 2]);
...
return parsedDate;
}
and so on...
Suggested reading:
http://docs.oracle.com/javase/tutorial/essential/regex/
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html