How to convert a vague timestamp with millisecond into java date - java

I have time stamp as 29-NOV-11 06.05.41.831000000 AM
Using SimpleDateFormat , i cannot really extract millisecond (.831000000) ....831 is millisecond (and i don't know why those 000000. But thats coming from different source. No control on that.)

The extra digits are nano-second. You can't include these in SimpleDateFormat or the standard libraries. The simplest thing to do in you case is to remove them before parsing the date/time.

java.time
Parse your date-time string into the OffsetDateTime using the timezone offset of UTC and convert the result into an Instant.
You can convert the Instant into milliseconds using Instant#toEpochMilli.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d-MMM-uu h.m.s.n a")
.toFormatter(Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
OffsetDateTime odt = OffsetDateTime.parse("29-NOV-11 06.05.41.831000000 AM", dtf);
Instant instant = odt.toInstant();
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output:
1322546741831
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

A working solution... A fairly strict regex for this is quite long-winded as you see.
String input = "29-NOV-11 06.05.41.831000000 AM";
input = input
.replaceFirst(
"(\\d+-\\w+-\\d+\\s\\d+\\.\\d+\\.\\d+\\.\\d{3})\\d{6}(\\s(\\w+))",
"$1$2");
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-yy HH.mm.ss.SSS aa");
Date date = sdf.parse(input);
System.out.println(sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
You could just use substr if the strings are always fixed width and you consider regex a bit of overkill.
input = input.substring(0, 22) + input.substring(28, 31);

If the timestamp is represented by a string you could use a regular expression to parse out the extra zeroes.

Related

How to add 'T' to UTC timestamp without T and also add 5 mins to it

I wan to convert the string d (date in UTC format) to String in UTC format with 'T' and increment 5 mins to time. Below is the code
public static void main (String args[]) throws ParseException
{
String d="2021-08-27 06:25:00.716241+00:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSXXX");
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date actualDate = format.parse(d);
String a=format1.format(actualDate);
System.out.println(a);
}
I get output as 2021-08-27T12:06:56 but I need String 'a' as 2021-08-27T06:25:00 and then add 5 mins to it and make it 2021-08-27T06:30:00
Please help
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String d = "2021-08-27 06:25:00.716241+00:00";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.SSSSSSXXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(d, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String str = odt.format(dtfOutput);
System.out.println(str);
// Add 5 minutes to it
odt = odt.plusMinutes(5);
str = odt.format(dtfOutput);
System.out.println(str);
}
}
Output:
2021-08-27T06:25:00
2021-08-27T06:30:00
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Convert a String (with reserved characters) to Date in Java

I want to convert a String (with reserved characters) to Date in Java
I have a string with some reserved characters in it. I am getting it from some source. Also I get the format of it from the same source. I tried to convert that string to a date but I was unable to.
The date I get:
{ts '2021-03-24 12:52:38.933'}
The format I get:
'{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}'
I tried with the sample code snippet but since {} are reserved characters and also ts is an invalid character for parsing, I am unable to parse it. Please help with how I can solve this.
Obviously I can do some string manipulation and convert it to a format I want but I don't want to do that.
String dateInString = "{ts '2021-03-24 12:52:38.933'}";
SimpleDateFormat sdf = new SimpleDateFormat("{ts' ''yyyy-MM-dd HH:mm:ss{.SSS}[Z]'''}", Locale.ENGLISH);
try {
Date date = sdf.parse(dateInString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
You need to escape ' with another '.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String dateInString = "{ts '2021-03-24 12:52:38.933'}";
SimpleDateFormat parser = new SimpleDateFormat("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
Date date = parser.parse(dateInString);
System.out.println(date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(formatter.format(date));
}
}
Output:
Wed Mar 24 12:52:38 GMT 2021
2021-03-24T12:52:38.933
ONLINE DEMO
Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String dateInString = "{ts '2021-03-24 12:52:38.933'}";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("'{ts '''yyyy-MM-dd HH:mm:ss.SSS'''}'", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(dateInString, parser);
System.out.println(ldt);
}
}
Output:
2021-03-24T12:52:38.933
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Date format of given String

What format the below date is in?
21-MAY-11 12.00.00.000000000 AM
i tried below but did not work. any clue?
DateTimeFormatter formatter_1 = DateTimeFormatter.ofPattern("dd-MMM-yy hh.HH.mm.SSSSSSSSS a");
There is no in-built pattern that you can use for it. You can build a case-insensitive DateTimeFormatter with Locale.ENGLISH to parse this string.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "21-MAY-11 12.00.00.000000000 AM";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("uu-MMM-dd hh.mm.ss.SSSSSSSSS a")
.toFormatter(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
System.out.println(ldt);
}
}
Output:
2021-05-11T00:00
Here, you can use yy instead of uu but I prefer u to y.
ONLINE DEMO
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Andy Turner in the comments is right.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yy hh:mm:ss.SSSSSSSSS a", Locale.ROOT);
LocalDateTime localDateTime = LocalDateTime.now();
String format = fmt.format(localDateTime);
System.out.println(format);
Use this one to format datetime.
DateFormat('dd-MMM-yy hh.HH.mm.SSSSSSSSS a').format(DateTime.now());

Localized date format in Java

I have a timestamp in millis and want to format it indicating day, month, year and the hour with minutes precission.
I know I can specify the format like this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm");
String formatted = simpleDateFormat.format(900000)
But I'd like the format to be localized with the user's locale. I've also tried
DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
DATE_FORMAT.format(new Date());
But it does not show the hour. How can I do it?
Is using joda time (http://joda-time.sourceforge.net/) out of the question? If not, then I would wholeheartedly recommend using this wonderful library instead of the cumbersome Java API.
If not, you could use DateFormat.getDateTimeInstance(int, int, Locale)
The first int is the style for hour, the other is the style for time, so try using:
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
String formattedDate = f.format(new Date());
System.out.println("Date: " + formattedDate);
See if this suits you.
Output for Locale.GERMANY:
Date: 25.07.13 10:57
Output for Locale.US:
Date: 7/25/13 10:57 AM
But it does not show the hour. How can I do it?
You have to call DateFormat.getDateTimeInstance(int, int, Locale)
DateFormat.getDateInstance(int, Locale) => Gets the date formatter with the given formatting style for the given locale.
While
DateFormat.getDateTimeInstance(int, int, Locale) => Gets the date/time formatter with the given formatting styles for the given locale.
Try some thing like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = simpleDateFormat.format(900000);
System.out.println(simpleDateFormat.parse(formatted));
You can use method getDateTimeInstance, of DateFormat. Here the getDateTimeInstance method takes 3 arguments
the style of Date field
the style of time field
the Locale using which pattern is auto extracted
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
System.out.println(DATE_FORMAT.format(d));
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.FRENCH);
System.out.println(DATE_FORMAT.format(d));
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
You can use DateTimeFormatter.ofLocalizedDateTime to obtain a locale-specific date format for the ISO chronology.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfLocalized = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
// Test
LocalDateTime date = LocalDateTime.now();
System.out.println(dtfLocalized.withLocale(Locale.US).format(date));
System.out.println(dtfLocalized.withLocale(Locale.UK).format(date));
System.out.println(dtfLocalized.withLocale(Locale.CHINESE).format(date));
System.out.println(dtfLocalized.withLocale(Locale.GERMAN).format(date));
System.out.println(dtfLocalized.withLocale(Locale.forLanguageTag("tr")).format(date));
System.out.println(dtfLocalized.withLocale(Locale.getDefault()).format(date));
}
}
Output:
5/8/21, 10:49 PM
08/05/2021, 22:49
2021/5/8 下午10:49
08.05.21, 22:49
8.05.2021 22:49
08/05/2021, 22:49
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using Joda-Time you could detect the system setting and use different time format:
String format;
if (DateFormat.is24HourFormat(context)) {
format = "MM/dd/yy, hh:mm";
}
else {
format = "MM/dd/yy, h:mm aa";
}
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
formatter.print(new DateTime());

Timezone conversion for a specific datetime in java

I will be giving input date time for a timezone and the timezone for the input date time and we want the relevant DateTime in the expected timezone.
And here is my method.
convertToTimezone("03/08/2010 20:19:00 PM","Asia/Shanghai","US/Central");
The above time is the time in Asia/Shanghai. We would like to know what is the corresponding time in US/Central.
It's working fine but I am getting a 1-hour difference from the actual time.
Can I know where I am going wrong?
Here is the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class DateUtil {
private static String format_date = "MM/dd/yyyy HH:mm:ss a";
public static void main(String a[]) {
try {
String sourceTimezone = "Asia/Shanghai";
String destTimezone = "US/Central";
String outputExpectedTimezone = convertToTimezone("03/08/2010 20:19:00 PM", sourceTimezone, destTimezone);
System.out.println("outputExpectedTimezone :" + outputExpectedTimezone);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone)
throws Exception {
String outputDate = null;
SimpleDateFormat format = new SimpleDateFormat(format_date);
format.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(inputDateTimezone));
calendar.setTime(format.parse(inputDate));
calendar.add(Calendar.MILLISECOND, -(calendar.getTimeZone().getRawOffset()));
calendar.add(Calendar.MILLISECOND, -calendar.getTimeZone().getDSTSavings());
calendar.add(Calendar.MILLISECOND, TimeZone.getTimeZone(destinationDateTimezone).getRawOffset());
outputDate = format.format(calendar.getTime());
return outputDate;
}
}
You shouldn't be adding anything to the calendar - that represents a specific instant in time. In fact, you don't need a calendar at all.
Instead, have two different formats, one for each time zone:
public static String convertToTimezone(String inputDate,
String inputDateTimezone,
String destinationDateTimezone)
throws Exception
{
SimpleDateFormat parser = new SimpleDateFormat(format_date);
parser.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Date date = parser.parse(inputDate);
SimpleDateFormat formatter = new SimpleDateFormat(format_date);
formatter.setTimeZone(TimeZone.getTimeZone(outputDateTimezone));
return formatter.format(date);
}
As an aside, I'd thoroughly recommend using Joda Time instead of the built-in date/time API.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
Since your input Date-Time does not have timezone information, parse it into a LocalDateTime
Attach the timezone of the input Date-Time with it to get a ZonedDateTime
Use the ZonedDateTime#withZoneSameInstant to convert this ZonedDateTime to the target ZonedDateTime
Return the formatted target ZonedDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "US/Central"));
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "America/Mexico_City"));
}
static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inputDate, dtf);
ZonedDateTime zdtInput = ldt.atZone(ZoneId.of(inputDateTimezone));
ZonedDateTime zdtDestination = zdtInput.withZoneSameInstant(ZoneId.of(destinationDateTimezone));
return zdtDestination.format(dtf);
}
}
Output:
03/08/2010 06:19:00 AM
03/08/2010 06:19:00 AM
ONLINE DEMO
Note: Avoid using the deprecated ID, US/Central. Use the standard ID, America/Mexico_City where Mexico City is the largest city in this timezone.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories