I have this code and I want to print out the time as String without the 'T' character between date and time.
String datetime4 =new StringBuilder().append(date4).append(time4).toString();
DateTime newdt=new DateTime(datetime4);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
newdt = formatter.parseDateTime(datetime4);
System.out.println(newdt);
Notice that date4 and time4 are String variables.
It will print:
2017-11-04T11:23:00.000+02:00
One way of doing it:
String date4 = "2017-02-02";
String time4 = "12:00:00";
//To parse it to Temporal object
DateTime dateTime = DateTime.parse(date4 +"T"+ time4);
// to output it as String in a prefered format (Thanks #Hugo)
System.out.println(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
If you prefer Java 8 you will need to use formatter I think, LocalDateTime doesn't overload toString in the same way as JodaTime.
But not sure why you want to do this? seems like just appending both date and time is enough? Anyway if you want to parse to the date you need to put T as is needed to pass it as a valid date time format to DateTime as well as LocalDateTime if using Java8, then you can reformat it as you wish.
String date4 = "2017-02-02";
String time4 = "12:00:00";
LocalDateTime dateTime = LocalDateTime.parse(date4 +"T"+ time4);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Using Java 8 LocalDateTime;
LocalDateTime dateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
DateTimeFormatter desiredFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
dateTime = LocalDateTime.parse("2017-06-01T12:10:10", formatter);
System.out.println(desiredFormat.format(dateTime));
When you do:
System.out.println(newdt);
You're printing the newdt variable, and internally println calls the toString() method on the object.
As this variable's type is DateTime, this code outputs the result of newdt.toString(). And Datetime.toString() method uses a default format that contains the "T".
If you want the output String to have a different format, you can do something like this:
System.out.println(newdt.toString("yyyy-MM-dd HH:mm:ss"));
The output will be:
2017-11-04 11:23:00
(without the "T")
You can use this version of toString with any pattern accepted by DateTimeFormatter.
You can also create another DateTimeFormatter for the format you want:
DateTimeFormatter withoutT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(withoutT.print(newdt));
The output will be the same, it's up to you to choose.
Related
I have a simple Date String headerValues[5]="24.11.1946". I just want to convert, parse it to a Date Object.
So I use
DateTimeFormatter formatter = ofPattern(("dd.MM.yyyy");
headerLine.setStartDate(LocalDate.parse(headerValues[5],datePattern));
Output is 2012-04-25 not my desired 24.11.1946???
Why???
EDIT
I tried this...
DateTimeFormatter datePattern = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY);
String date = "24.11.1946";
System.out.println("Date = "+ LocalDate.parse(date,datePattern));
Output is...
Date = 1946-11-24
This part of your code...
LocalDate.parse(date,datePattern)
creates a LocalDate instance.
Hence in this line of your code...
System.out.println("Date = "+ LocalDate.parse(date,datePattern));
you are actually calling method toString() of class LocalDate.
From the javadoc of that method...
The output will be in the ISO-8601 format uuuu-MM-dd.
You don't want that format. You want the format of your datePattern object. Hence you should change the last line of the code you posted to...
System.out.println(datePattern.format(LocalDate.parse(date,datePattern)));
In other words, the same DateTimeFormatter object can be used both to parse a String to a date and to format a date to a String.
For example you have:
String datetime = new String("2008-05-09");
Timestamp.valueOf( datetime )
The value will be: 2008-05-09 00:00:00.0 without any exception.
Another example:
String datetime = new String("2008-05-09 13:34");
Timestamp.valueOf( datetime )
The value will be: 2008-05-09 13:34:00.0 without any exception.
Thanks,
If I understand you right, you are going to get a string that is only part of a timestamp and you want to parse it? You can use SimpleDateFormat if you know the format you will receive. https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
I assume you want to convert Strings into timestamp objects regardless of whether they contain time part or not.
You can do it by this way: String -> Date -> TimeStamp
To convert String into Date, you can use DateUtils library (with multiple date formats) and then, you can convert date into timestamp. Have a look at the below example:
String[] dateFormats = new String[]{"yyyy-MM-dd", "yyyy-MM-dd hh:mm", "yyyy-MM-dd hh:mm:ss"};
for(String dateString : new String[]{"2008-05-09", "2008-05-09 13:34", "2008-05-09 13:34:40"}){
Date date = DateUtils.parseDate(dateString, dateFormats);
Timestamp timeStamp = new Timestamp(date.getTime());
System.out.println(timeStamp);
}
How to convert from "2014-06-16T07:00:00.000Z" to "16-JUN-14 07:00:00" using joda time API?
The below code is throwing the exception
java.lang.IllegalArgumentException: Illegal pattern component: T
at org.joda.time.format.DateTimeFormat.parsePatternTo(DateTimeFormat.java:570)
at org.joda.time.format.DateTimeFormat.createFormatterForPattern(DateTimeFormat.java:693)
at org.joda.time.format.DateTimeFormat.forPattern(DateTimeFormat.java:181)
at com.joda.JodaTimeTest.convertJodaTimezone(JodaTimeTest.java:59)
at com.joda.JodaTimeTest.main(JodaTimeTest.java:50)
This is the code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-ddTHH:mm:ssZ");
DateTime dt = formatter.parseDateTime(dstDateTime.toString());
You need to enclose the literal T within single quotes. Also the milliseconds are not properly patterned. You need to include SSS for the milliseconds. Have a look at the patterns here for more info.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Update: To format the DateTime into a String representation of your choice, you need to do this.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime dt = formatter.parseDateTime(dstDateTime.toString()); // You get a DateTime object
// Create a new formatter with the pattern you want
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("dd-MMM-yy HH:mm:ss");
String dateStringInYourFormat = formatter2.print(dt); // format the DateTime to that pattern
System.out.println(dateStringInYourFormat); // Prints 16-Jun-14 12:30:00 because of the TimeZone I'm in
Either specify the timezone yourself or your default system timezone would be taken.
You need to change
"yyyy-MM-ddTHH:mm:ssZ"
To
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
Now
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z");
DateTime dt = formatter.parseDateTime("2014-06-16T07:00:00.000Z");
System.out.println(dt);
Output:
2014-06-16T07:00:00.000+05:30
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)