How to print date string with ISO8601 format? - java

Please help me to print my date in below format
Example: 2020-08-05T16:17:10,777
I tried with below date converter but it is not giving the output that I want.
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String text = sdf.format(requestTime);
loggdata.append(REQUEST_TIME + requestDate);
I got date printed like "2020-08-20T06:26:09.003763Z". Date is in UTC tomezone and format is different.
I can see many question and answers here in stackoverflow. But here in my case I need exactly this format 2020-08-05T16:17:10,777 see the last portion ",777".
Also I need to display the time in local timezone

Found a solution for the same. I have used "LocalDateTime" for the same.
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss,SSS");
String dateInString= now.format(formatter);
It displayed date like this "2020-08-20T21:18:56,321"

Related

Converting date string build from date and time picker [duplicate]

This question already has answers here:
Parse String to Date with Different Format in Java
(10 answers)
Closed 1 year ago.
I have a date and time picker and I build a string date using these two. Here's a sample date and time string.
"11/6/2013 09:23"
Now I need to convert them into a date and convert them to this format "yyyy-MM-dd'T'HH:mm:ss.SSS".
My problem is I'm having this error in my logcat:
11-06 21:23:53.060: E/Error(26255): Unparseable date: "11/6/2013 09:23" (at offset 2)
I'm using this code to do the conversion of string to date, and the date to a formatted string.
Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = d.toString();
When I use new Date and get the current date, it works fine. I guess the format of my string is wrong. But I'm displaying it on an edittext in that format. I want to stay it in that way. Is there anyway to convert this string format to a date? Any ideas guys? Thanks!
I think you are trying to do 2 things at once. In order to convert any String to another String in a different format you need to:
Parse the string with a DateFormat containing the current format, this returns a Date; then
take your newly obtained Date and format it under the desired DateFormat
SimpleDateFormat formatOne = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = formatOne.parse(etaToDeliverArrivedAtShipper.getText().toString());
SimpleDateFormat formatTwo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS",Locale.getDefault());
String result = formatTwo.format(date)
you are trying to parse in yyyy-MM-dd'T'HH:mm:ss.SSS but it is not. it is probably yyyy/M/dd HH:mm:ss
What you probably want is:
Date d = new SimpleDateFormat("yyyy/M/dd HH:mm:ss", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).format(d);
This is simply because your pattern is not matching the date string you are trying to parse. There are 3 errors in your pattern :
You use MM which means the month should be on two digits, while in the date it is only 1 digit
You use .SSS which means there are milliseconds but your date is not that precise
You are using the wrong delimiter
So the right pattern should be : yyyy/M/dd HH:mm:ss
To get the desired format, then create a new SimpleDateFormat object with the desired pattern and use the parse(Date) method giving it the Date object previously returned by parse().

Getting formatted date in date format rather than String

I'm running the program written below, but instead of printing in mm/dd/yyyy hh:mm format it prints in the normal date format(ie. Day Date and time)
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy hh:mm");
Date date = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
The reason i'm doing this is because the existing method accepts parameters in Date format, so i need to send the above mentioned date object to it.
Please point out the mistake or suggest some other alternative.
Thanks
Date objects don't have a format. The Date class is a wrapper around a single long, the number of milliseconds since the epoch. You can't "format" a Date, only a String. Pass around a Date/Calendar internally, and format it whenever you need to display it, log it, or otherwise return it to the user.
Change the format to MM/dd/yyyy. Month is denoted by capital M.
Check below URL for valid formats
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your formatter works quite fine (apart from the mm vs. MM bug). You get a formatted string from the date and then create a copy from your date by parsing the formatted string:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date now = Calendar.getInstance().getTime();
String formattedNow = sdf.format(now); // == "09/24/2013 01:59"
Date now2 = sdf.parse(formattedNow); // == now

How to get Timestamp with AM/PM in java

I have a date as String , which needs to be converted in to Time Stamp with AM/PM . I tried the below way, I'm getting the proper date format but didn't get in AM/PM.
Can any one please help ?
code Snippet:
String dateString = "10/10/2010 11:23:29 AM";
SimpleDateFormat sfdate = new SimpleDateFormat("MM/dd/yyy HH:mm:ss a");
Date date = new Date();
date = sfdate.parse(dateString);
System.out.println(new Timestamp(date.getTime()));
Which gives me the output as below :
2010-10-10 11:23:29.0
But I needs it like this
2010-10-10 11:23:29.00000000 AM
Kindly help me please.
Why create a timestamp ? When you can just :
SimpleDateFormat sfdate = new SimpleDateFormat("MM/dd/yyy HH:mm:ss a");
Date date = new Date();
date = sfdate.parse(dateString);
System.out.println(sfdate.format(date) );
Output:
10/10/10 11:23:29 AM
Try:
System.out.println(sfdate.format(date));
As your last line rather than the one that you have at current.
Timestamp.toString() prints to a specific format: yyyy-mm-dd hh:mm:ss.fffffffff. The Timestamp object itself should be correct, if that's all you are looking for.
If you then want to define another format in order to print it as you like, that would require you to format Date object, using an appropriate pattern for the output format you are looking for.
What you're seeing is the result of Timestamp.toString(). The actual value in the Timestamp object instance is valid.
If you're getting an error in a subsequent SQL operation, please post that error along with the code you're using.

java Date and time format

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.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

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.)

Categories

Resources