Joda-Time, How to pick up format for string parsing? - java

Following code using Joda-Time library
Long timestamp = DateTime.parse(dateInString,DateTimeFormat.shortTime()).getMillis();
generates:
java.lang.IllegalArgumentException: Invalid format: "12.05.2014 11:42:35.808" is malformed at ".05.2014 11:42:35.808"
I tryed all DateTimeFormat.* but each format produces error.
How to fix it?

Build a DateTimeFormatter matching your pattern, and use that. Your pattern certainly isn't a "short time" pattern, given that you've got a date in there as well...
For example:
// Possibly MM.dd.yyyy - we don't know what 12.05.2014 is meant to represent
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss.SSS");
.withLocale(Locale.US)
.withZoneUTC(); // Adjust accordingly
DateTime dateTime = formatter.parse(text);
long millis = dateTime.getMillis();

try this
DateTimeFormatter pattern = DateTimeFormat.forPattern("dd.MM.yyy hh:mm:ss.SSS");
Long timestamp = DateTime.parse(dateInString,pattern).getMillis();

import java.util.*;
import java.text.*;
Date DateNow= new Date( );
SimpleDateFormat sdf =new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss");
String timestamp= sdf.format(DateNow);

Related

Convert custom date string(with am/pm) to UTC Date Time using java

I just need sample code block or suggestion to convert the following date string to utc time in format yyyy-MM-dd HH:mm:ss?
sample date string:11/23/2017 09:44am
there are similar questions like this but my test data is with am/pm.So pls dont consider this as duplicate
You could use the Java 8 time package:
String input = "11/23/2017 09:44am";
String format = "MM/dd/yyyy hh:mma";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime date = LocalDateTime.parse(input, formatter);
System.out.printf("%s%n", date);
But the problem is: this throws a DateTimeParseException, because of the lowercase 'am'.
I looked up in the docs, but I couldn't see a standard way to parse lowercase 'am' or 'pm' as as meridiem designator1. You'll end up manually replacing them:
input = input.replace("AM", "am").replace("PM","pm");
As mentioned by #OleVV in the comments, you can use a DateTimeFormatterBuilder and specify that the parsing should be case-insensitive:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(format)
.toFormatter();
Then you can use this formatter as argument to the LocalDateTime.parse method.
Another answer of the aforementioned post provides a solution where you can override the AM/PM symbols with the lowercase variants.
1 Interestingly, the SimpleDateFormat does support the parsing of lowercase am/pm.
The sample code below should do the conversion correctly.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConversion {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sampleDateString = "11/23/2017 09:44am";
try {
Date convertDate = formatter.parse(sampleDateString);
System.out.println(OutputFormatter.format(convertDate));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This is to declare the date string to be parsed.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
and the output date as well
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
At first you need to create a SimpleDateFormat with the proper pattern. This class helps you to parse your string to java.util.Date (more info here):
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma");
If your original string-date is in a special timezone then you need to instruct the parser to use this timezone:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Then you need to parse the string to date:
Date d = sdf.parse("11/23/2017 09:44am");
Finnaly you have to convert the timezoned date to UTC.
Please find bellow the full code snippet:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Date d = sdf.parse("11/23/2017 09:44am");
System.out.println(toUtcZonedDateTime(d));
}
public static ZonedDateTime toUtcZonedDateTime(final Date date) {
if (date == null) {
return null;
}
final ZoneId utcZone = ZoneOffset.UTC;
return ZonedDateTime.ofInstant(date.toInstant(), utcZone);
}
Output:
2017-11-23T08:44Z
SimpleDateFormat's javadoc lists all the options, including "a" for am/pm marker.
In you case, you need:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa")

Joda time convert query

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

Java How to convert time literal to long value?

If I have a time (String) coming into my class with the following format
2013-01-25T07:31:51.00Z
How do i turn that into a long?
I don't even know what format that is to put in to a DateFormat. Anyone else have a clue?
DateFormat formatter = new SimpleDateFormat(" MMM yyyy HH:mm:ss z");
Desired results
long time = changeMe("2013-01-25T07:31:51.00Z");
System.out.print(time);
//012432423 <-- But only the actual long
Looks like you have iso8601 format here. Try this:
import javax.xml.bind.DatatypeConverter;
public long changeMe(String isoTimestamp) {
final Calendar c = DatatypeConverter.parseDateTime(isoTimestamp);
return c.getTimeInMillis();
}
BTW c.getTime() returns Date object, if you prefer.
See also:
Converting ISO 8601-compliant String to java.util.Date
using the excellent jodatime library:
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
long time = fmt.parseDateTime("2013-01-25T07:31:51.00Z").getMillis();

Fail to parse date with time zone with Joda Time

I am trying to use Joda Time both for formatting DateTime objects to String and than parse these strings back to DateTime. But I am failing to so when the pattern includes z:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss.SSS z");
String dts = dtf.print(System.currentTimeMillis());
System.out.println(dts);
DateTime dt = dtf.parseDateTime(dts);
The above code is throwing exception when the parsing the String to DateTime takes occurred.
Do you have any idea?
Yosi
You can do:
DateTime dt = new DateTime();
System.out.println(dt.toString("dd-MM-yyyy HH:mm:ss.SSS z"));
Have a look in the user guide
The Pattern is not correct, maybe try this one
DateTimeFormatter dtf = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss.SSS'z" );
this worked for me

Extract time from date String

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)

Categories

Resources