Date Format Fail - java

I am trying to format the following input date: "2019-02-12 18:00:40""
to the following format "dd-MM-yyyy". However, I am experiencing mixed results with the date formatter method I created below and the output is as follows
"Wed Aug 11 00:00:00 GMT+02:00 17"
private String formatDate(String dateT) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dateT);
return date.toString();
}

As mentioned, you'll need two formats to get your desired result.
If you can use Java8+, I suggest using LocalDateTime and DateTimeFormatter (instead of SimpleDateFormat):
String stamp = "2019-02-12 18:00:40";
LocalDateTime ldt = LocalDateTime.parse(stamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(ldt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")));
Output:
12-02-2019
Edit:
If you really must use the outdated classes, you can apply the same principle with SimpleDateFormat:
String stamp = "2019-02-12 18:00:40";
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dt1.parse(stamp);
SimpleDateFormat dt2 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(dt2.format(date));

As suggested by #Robert. This was the solution I ended up using with two simpledateformatters.
private String formatDate(String date) throws ParseException {
SimpleDateFormat inputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = inputDate.parse(date);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = formatter.format(currentDate);
return formattedDate;
}

Related

How do I change 'AM' to 'PM' in a Date Object JAVA [duplicate]

This question already has answers here:
Comparing two times in android
(4 answers)
12:xx shown as 00:xx in SimpleDateFormat.format("hh:mm:ss")
(1 answer)
Closed 3 years ago.
I am trying to use Date objects and calculate time differences for an android app. But I face a problem when time is in '12:00'. I mean when I input date as 12:12:00 Java AM/PM formatter returns 12:12:00AM but it should be 12:12:00PM.
I can't find any way to solve it.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
It returns 12:12:00 AM
but it should be 12:12:00 PM for correct calculations
In Line:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
The hh makes sure that hours are parsed as AM/PM values b/w 1-12. To get the desired result, you can use HH marker which parses hour values between 0-23. So, the code should be:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Use DateTimeFormatter and LocalDateTime
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(stringDate, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(formatter2.format(date));
You might also want to set a Locale for your second formatter depending on where you live.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.US);
System.out.println(formatter2.format(date));
12:12:00 PM
Pass the AM/PM in the time
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
Try to do it the modern way, that is using java.time:
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime datetime = LocalDateTime.parse(stringDate, dtf);
DateTimeFormatter dtfA = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
System.out.println(datetime.format(dtfA));
// receive the time part and format it
LocalTime timePart = datetime.toLocalTime();
DateTimeFormatter tf = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(timePart.format(tf));
This outputs
2019-09-13 12:12:00 PM
12:12:00 PM
on my system.
Note that your pattern String used for parsing is wrong since you are not using capital "H" for the hours of day, but "h" instead. That will definitely not work (correctly).
Two solutions,
1.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
2.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
If you are using java 8 or above then you should definitely use LocalDateTime and DateTimeFormatter makes it way easier to work with date times.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
String am = LocalDateTime.now().format(formatter);
String pm = LocalDateTime.now().plusHours(2).format(formatter);
System.out.println(am);
System.out.println(pm);
Now I am assuming that I run this code during am hours just 2 hours before it changes to pm you can also try out #Joakim Danielson answer which should not be dependent on when it is run.
checkout the documentation for LocalDateTime and DateTimeFormatter

convert string into date format

I want this format 6 Dec 2012 12:10
String time = "2012-12-08 13:39:57 +0000 ";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
System.out.println("Time: " + date);
You need to first parse your date string (Use DateFormat#parse() method) to get the Date object using a format that matches the format of date string.
And then format that Date object (Use DateFormat#format() method) using the required format in SimpleDateFormat to get string.
String time = "2012-12-08 13:39:57 +0000";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(time);
String str = new SimpleDateFormat("dd MMM yyyy HH:mm:ss").format(date);
System.out.println(str);
Output: -
08 Dec 2012 19:09:57
Z in the first format is for RFC 822 TimeZone to match +0000 in your date string. See SimpleDateFormat for various other options to be used in your date format.
change SimpleDateFormat to:
String time = "2012-12-08 13:39:57 +0000";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
Date date = sdf.parse(time);
DateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
String formatedTime = sdf.format(date);
System.out.println("Time: " + formatedTime);
Take a look at SimpleDateFormat. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
Date date=simpleDateFormat.parse("23-09-2008");
You can use the SimpleDateFormat Class to do this!
such:
DateFormat mydate1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = mydate1.parse(time);

How to parse String "24-10-2012" into Date ( dd-mm-yyyy) format?

I am using jdk- 1.6.
I am try to parse String "24-10-2012" date to Date (24-10-2012) but i am getting this error:
java.text.ParseException: Unparseable date: "18-11-2012"
java.text.DateFormat.parse(DateFormat.java:354)
I am parsing like this:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = "24-10-2012";
Date date = formatter.parse(currentDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = "24-10-2012";
System.out.println(formatter.parse(currentDate));
prints
Wed Oct 24 00:00:00 CEST 2012
Your problem cannot be reproduced with the code you have posted.
My hypothesis: your exception is thrown from a piece of code other than the one you are accusing of the error. You could try carefully analyzing the stack trace in order to track down the real culprit.
Date in java does not hold any format. Read more...
When I run
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = "24-10-2012";
Date date = formatter.parse(currentDate);
System.out.println(date);
System.out.println(formatter.format(date));
I get
Wed Oct 24 00:00:00 BST 2012
24-10-2012
which is as I expected. Can you clarity what the problem is?
You can use this for the format "dd-mm-yyyy"
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = "24-10-2012";
Date date = formatter.parse(currentDate);
System.out.println(formatter.format(date));
import java.util.Date;
import java.text.SimpleDateFormat;
public class SimpleFormatDate
{
public static void main(String args[]){
Date todaysDate = new java.util.Date();
// Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
// Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
// Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
}
}
output
Formatted date is ==>2008-10-10 13:03:54
Formatted date is ==>2008-10-10
Formatted date is ==>10/10/2008
Wait a second.. Why u need to parsing that if u have a right value ?
Anyway, i use this :
SimpleDateFormat oFormat = new SimpleDateFormat("yyyy-MM-dd");
String sDate = oFormat.format("24-10-2012");
it will appearing date like 2012-10-24. So if u want to parsing to dd-MM-yyyy, u just need change the format to what u want.
NB : Sorry if my english is bad. :D

Converting string date to date

How would I convert a String date in the form of 24/04/2012 to a date variable in the format of 24-Apr-12, which can later be passed into my Oracle database.
I have tried this but it says the string date is unparsable:
DateFormat format = new SimpleDateFormat("dd-MMM-yy");
Date newDate = (Date) format.parse(date);
I think you are confusing parsing and formatting, try this:
String old_date = "24/04/2012";
DateFormat old_format = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = (Date) old_format.parse(old_date);
DateFormat new_format = new SimpleDateFormat("dd-MMM-yy");
String date = new_format.format(newDate);
System.out.println(date);
You are doing this backwards:
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = format.parse(date);
DateFormat formatOutput = new SimpleDateFormat("dd-MMM-yyyy");
String output = formatOutput.format(newDate);
But if what you are doing is passing the date to Oracle, you should really use a PreparedStatement
Your date format should be "dd/MM/yyyy"
SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yy");
DateTime newDate = sdf.format(date);
Try DateFormat format = new SimpleDateFormat("dd/MM/yyyy")
Why don't you try using java.sql.Date.
For example:
Date newDate = new java.sql.Date(date.getTime());
So you can just give an generic sql object for date.
The Date class of Java is quite difficult to use in many cases. I recommend the use of the much better Joda Time classes:
DateTimeFormatter oldFormat = DateTimeFormat.forPattern("dd/mm/yyyy");
DateTimeFormatter newFormat = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = oldFormat.parseDateTime("24/04/2012");
String newDate = newFormat.print(dateTime);

Java Date Formatter

I am getting date format as "YYYY-mm-dd hh:mm" as formatter object.
How can I format the input formatter object to get only "YYYY-mm-dd";?
I am getting date format as
"YYYY-mm-dd hh:mm" as formatter
object. How can i format the input
formatter object to get only
"YYYY-mm-dd";
You can not have date as YYYY-mm-dd it should be yyyy-MM-dd. To get date in yyyy-MM-dd following is the code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Format formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date;
try {
date = (Date)((DateFormat) formatter).parse("2011-04-13 05:00");
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
System.out.println(s);
} catch (ParseException e) {
e.printStackTrace();
}
Use SimpleDateFormat
String myDateString = "2009-04-22 15:51";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(outFormat.format(inFormat.parse(myDateString)));
If you're getting a date in the format "YYYY-mm-dd hh:mm" and you want it as "YYYY-mm-dd" I suggest you just use inputDate.substring(0, 10).
In either way, beware of potential Y10k bugs :)
Following sample formate date as yyyy-MM-dd in Java
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();
System.out.println("Now: "+formatter.format(now.getTime()) );
Yes, SimpleDateFormat is what you are looking for
http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/builds/latest/html/en/api/java/text/SimpleDateFormat.html
SimpleDateFormat is what you're looking for.
Try this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Use this code:
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
System.out.println("formatted time==>" + formattedDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Other answers such as the one by user2663609 are correct.
As an alternative, the third-part open-source replacement for the java.util.Date/Calendar classes, Joda-Time, includes a built-in format for your needs.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String stringIn = "2011-04-07";
// Returns a formatter for a full date as four digit year, two digit month of year, and two digit day of month (yyyy-MM-dd).
DateTimeFormatter formatter = ISODateTimeFormat.date().withZone( DateTimeZone.forID( "Europe/London" ) ).withLocale( Locale.UK );
DateTime dateTime = formatter.parseDateTime( stringIn ).withTimeAtStartOfDay();
String stringOut = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime.toString() );
System.out.println( "stringOut: " + stringOut );
When run…
dateTime: 2011-04-07T00:00:00.000+01:00
stringOut: 2011-04-07
This question has so many good answers !! , here comes another one more generic solution
public static String getDateInFormate(String oldFormate , String newFormate , String dateToParse){
//old "yyyy-MM-dd hh:mm"
//new yyyy-MM-dd
//dateTopars 2011-04-13 05:00
String formatedDate="";
Format formatter = new SimpleDateFormat();
Date date;
try {
date = (Date)((DateFormat) formatter).parse(dateToParse);
formatter = new SimpleDateFormat(newFormate);
formatedDate = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String strDate = entry_date;
System.out.println("strDate*************"+strDate);
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date yesterday =subtractDay( date);
String requiredDate = df.format(yesterday);
System.out.println("110 days before*******************"+requiredDate);
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -110);`enter code here`
return cal.getTime();
}
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
For parsing input define a formatter:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ROOT);
Parse:
String input = "2019-01-21 23:45";
LocalDateTime dateTime = LocalDateTime.parse(input, FORMATTER);
System.out.println(dateTime);
Output so far:
2019-01-21T23:45
Format output:
String output = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(output);
2019-01-21
Tutorial link
Trail: Date Time (The Java™ Tutorials) explaining how to use java.time.

Categories

Resources