I have the following scenario :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));
gives an output
Tue May 31 00:00:00 SGT 2011
but I want the output to be
31/05/2011
I need to use parse here because the dates need to be sorted as Dates and not as String.
Any ideas ??
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
You need to go through SimpleDateFormat.format in order to format the date as a string.
Here's an example that goes from String -> Date -> String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
If you want to simply output a date, just use the following:
System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());
As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:
String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());
You can also customize your output by following the Java API on Date/Time conversions.
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).
This will help you.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
print (df.format(new Date());
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
This looks more compact. Finishes in a single line.
import org.apache.commons.lang3.time.DateFormatUtils;
System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));
Related
I have date 2016-03-30T23:59:59.000000+0000. May I know what format it is in.
because if I use yyyy-MM-dd'T'HH:mm:ss.SSS, it is throwing an exception
SimpleDateFormat gives you the answer:
yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ
If you really have microseconds different from zero then I strongly advise not to use SimpleDateFormat but Java-8-Time-API or another time library which can handle microseconds. And this is not the only case where the old API proves to be very limited.
Negative example for SimpleDateFormat (broken, milliseconds disappear!!!):
String input = "2016-03-30T23:59:59.123456+0530";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(sdf.parse(input))); // 2016-03-30T18:32:02.000456+0000
Java-8-example (works):
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
OffsetDateTime odt = OffsetDateTime.parse(input, dtf);
System.out.println(odt); // 2016-03-30T23:59:59.123456+05:30
If you never have microseconds but only milliseconds and want to insist on using the old API then you might try following hack:
String input = "2016-03-30T23:59:59.123000+0530";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'xxx'Z");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf2.format(sdf1.parse(input.replace("000", "xxx"))));
2016-03-30T18:29:59.123+0000
However, this "solution" breaks for year 2000 (you can find a better one by further string preprocessing), and eventually available microseconds get lost. So using SimpleDateFormat is a bad idea here.
I am facing an issue when I convert my string to date format.
This is what I have tried -
First try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
date = df.parse(completionDate1);
System.out.println(date); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
Second try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("yyyy/MM/dd").parse(completionDate1);
System.out.println(completionDate); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
The output I'm expecting is that, the completionDate should be Date format not String. I'm just printing the completionDate just to make sure the date format is getting getting converted.
The main intention of getting it in date format is I need this for an Update query so it has to be Date and not String.
Kindly let me know where I'm going wrong. I need this date format as I need to store this date in a database.
Thanks
You have to format the date after parsing it but your parsing format is also incorrect so its giving wrong output. Try
String completionDate1 = "21/10/2016";
System.out.println(completionDate1);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
date = df.parse(completionDate1);
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df1.format(date));
DEMO
Wrong pattern
First problem is that your defined parsing pattern does not match your input string. For 21/10/2016 pattern should be dd/MM/yyyy.
java.sql.Date versus java.util.Date
Second problem is that for database access you should be using the java.sql.Date class for a date-only value without time-of-day and without time zone. Not to be confused with java.util.Date which is a date and time-of-day value. You should specify the fully-qualified class name in such discussions as this Question.
Neither of these classes have a “format”. They have their own internal representation, a count from epoch.
java.time
Third problem is that you are using old outdated classes. In Java 8 and later, use java.time framework now built-in. In Java 6 & 7, use its back-port, the ThreeTen-Backport project. For Android, use the adaptation of that back-port, ThreeTenABP.
In the java.time classes we now have the LocalDate class for date-only values.
String input = "21/10/2016"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Hopefully some day JDBC drivers will be updated to directly use the java.time types. Until then, use the new methods added to the old java.sql types to convert.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
Now pass that java.sql.Date object to the setDate method on a PreparedStatement object for transmission to a database.
Note that at no time did we make use of any more strings. We went from original input String to java.time.Date to java.sql.Date.
At no point did we use java.util.Date. Check your import statements to eliminate java.util.Date.
By the way, to go the other direction from java.sql.Date to LocalDate:
LocalDate localDate = mySqlDate.toLocalDate();
Use below code
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("dd/MM/yyyy").parse(completionDate1);
String date = new SimpleDateFormat("yyyy/MM/dd").format(completionDate);
System.out.println(date);
You can try this
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String completionDate = df.format(request.getParameter("completion_date"));
System.out.println(completionDate);
how to format "2011-10-25T13:00:00Z" string into date and time
i used simple date format class
SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
but it only giving the date value. not time values
please help me to solve this problem
Use the format "yyyy-MM-dd'T'HH:mm:ss'Z'" for parsing this date format. See the documentation of SimpleDateFormat for more info. Code will look like this
String dateStr = "2011-09-19T15:57:11Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
Date date = new SimpleDateFormat(pattern).parse(dateStr);
This is because "yyyy-MM-dd" only mentions year (yyyy), month (MM) and date (dd). Try adding hh:mm if you want hours and minutes.
Example:
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm");
System.out.println(sim.format(new Date())); // prints "2011-10-27 01:56"
The full documentation of the format-string and its parts is found here. The documentation includes this example:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" - 2001-07-04T12:08:56.235-0700
Perhaps it's something like that you're looking for.
I want to convert the timestamp 2011-03-10T11:54:30.207Z to 10/03/2011 11:54:30.207. How can I do this? I want to convert ISO8601 format to UTC and then that UTC should be location aware. Please help
String str_date="2011-03-10T11:54:30.207Z";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
date = (Date)formatter.parse(str_date);
System.out.println("output: " +date );
Exception :java.text.ParseException: Unparseable date: "2011-03-10T11:54:30.207Z"
Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.
However, here's a sample program using Joda Time which parses the text into a DateTime and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2011-03-10T11:54:30.207Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTime();
DateTime dt = parser.parseDateTime(text);
DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
System.out.println(formatter.print(dt));
}
}
Yes. you can use SimpleDateFormat like this.
SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));
Output
OldDate-->2011-03-10T11:54:30.207Z
NewDate-->10-Mar-2011 11:54:30.207
Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
You might want to have a look at joda time, which is a little easier to use than the java native date tools, and provides many common date patterns pre-built.
In response to comments, more detail:
To do this using Joda time, you need two DateTimeFormatters - one for your input format to parse your input and one for your output format to print your output. Your input format is an ISO standard format, so Joda time's ISODateTimeFormat class has a static method with a parser for it already: dateHourMinuteSecondMillis. Your output format isn't one they have a pre-built formatter for, so you'll have to make one yourself using DateTimeFormat. I think DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS"); should do the trick. Once you have your two formatters, call the parseDateTime() method on the input format and the print method on the output format to get your result, as a string.
Putting it together should look something like this (warning, untested):
DateTimeFormatter input = ISODateTimeFormat.dateHourMinuteSecondMillis();
DateTimeFormatter output = DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
String outputFormat = output.print( input.parseDate(inputFormat) );
Hope this Helps:
public String getSystemTimeInBelowFormat() {
String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
return timestamp;
}
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)
How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)