Convert Date string with Time to long date - java

I have a string with date "10:00 AM 03/29/2011", I need to convert this to a long using Java, I cant use Date because its deprecated and it was not giving me the time correctly.. so i looked online to see how to come about it but still no luck. First time using java.

The problem is you're parsing the data and then messing around with it for no obvious reason, ignoring the documented return value for Date.getYear() etc.
You probably just want something like this:
private static Date parseDate(String text)
throws ParseException
{
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy",
Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.parse(text);
}
If you really want a long, just use:
private static long parseDate(String text)
throws ParseException
{
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy",
Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.parse(text).getTime();
}
Note that I'm punting the decision of what to do if the value can't be parsed to the caller, which makes this code more reusable. (You could always write another method to call this one and swallow the exception, if you really want.)
As ever, I'd strongly recommend that you use Joda Time for date/time work in Java - it's a much cleaner API than java.util.Date/Calendar/etc.

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:
Parse the Date-Time string into LocalDateTime.
Convert the LocalDateTime to Instant.
Convert Instant to the Epoch milliseconds.
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "10:00 AM 03/29/2011";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:m a M/d/u", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
long epochMillis = instant.toEpochMilli();
System.out.println(epochMillis);
}
}
Output in my timezone, Europe/London:
1301389200000
ONLINE DEMO
Some important notes about this code:
ZoneId.systemDefault() gives you to the JVM's ZoneId.
If 10:00 AM 03/29/2011 belongs to some other timezone, replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
If 10:00 AM 03/29/2011 is in UTC, you can do either of the following:
get the Instant directly as ldt.toInstant(ZoneOffset.UTC) or
replace ZoneId.systemDefault() with ZoneId.of("Etc/UTC") in this code.
The timezone of the Ideone server (the online IDE) is UTC whereas London was at an offset of +01:00 hours on 03/29/2011 and hence the difference in the output from my laptop and the one you see in the ONLINE DEMO. Arithmetic: 1301389200000 + 60 * 60 * 1000 = 1301392800000
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.

Related

Java date format different results

I am looking to understand why this code is giving me different results.
I want to format 2022-10-12T00:00:00.000Z into yyyy-MM-dd format.
Result when I run it online in Java IDE: 2022-10-12
But on my own computer the result is: 2022-10-11
String date = "2022-10-12T00:00:00.000Z";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
TemporalAccessor ta = DateTimeFormatter.ISO_INSTANT.parse(date);
Instant i = Instant.from(ta);
Date d = Date.from(i);
dateFormat.format(d);
The answer by Louis Wasserman is correct. A couple of important points:
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.
SimpleDateFormat does not have a way to specify a time-zone in the pattern. The way to specify a time-zone with SimpleDateFormat is by calling SimpleDateFormat#setTimeZone(java.util.TimeZone). Without setting time-zone explicitly, SimpleDateFormat uses the system time-zone. You could get the desired result had you done the following
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
dateFormat.format(d);
The solution
I want to format 2022-10-12T00:00:00.000Z into yyyy-MM-dd format
Demo with java.time API:
Since your date-time string is in UTC and you want to get just date part from the UTC date-time:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "2022-10-12T00:00:00.000Z";
// Parse the given text into an OffsetDateTime and format it
String desiredString = OffsetDateTime.parse(strDate)
.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(desiredString);
}
}
Output:
2022-10-12
Learn more about the modern Date-Time API from Trail: Date Time.
If the online IDE is running in a different time zone than you, it might be 10-12 in one time zone and still 10-11 in another. You have specified Z as the time zone of the input, but you have not specified the time zone used in formatting the date.
It may be that Date/SimpleDateFormat don’t support time zone.
You can try using the java.time package:
LocalDate.now()
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now())

Can I instantiate a new Date already with a timezone in Java?

I need to generate a new Date(); already with the correct time zone, because I need to record the date and time that a new data is received on my server. (I know that you can use the SimpleDateFormat, but it requires to parse a already created string).
I'm using Java + Spring Boot.
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: You can use ZonedDateTime with the applicable ZoneId.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// Use the applicable ZoneId
ZoneId zoneId = ZoneId.of("Asia/Dubai");
ZonedDateTime now = ZonedDateTime.now(zoneId);
System.out.println(now);
}
}
Output from a sample run:
2021-10-30T02:26:07.471319+04:00[Asia/Dubai]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
A note on java.util.Date:
A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
* 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. Note that Android 8.0 Oreo already provides support for java.time.
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");

How can I convert epoch time to date and time in Java?

I need to convert epoch timestamp to date and time.
I have used the following code to convert but it converts to a wrong date, year and time.
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date (1319286637/1000));
Expected output was today’s date at some time, but the result I got was:
01/01/1970 05:51:59
The Date(long) constructor takes milliseconds. You should be multiplying by 1000, not dividing the epoch time you have.
In brief:
Instant.ofEpochSecond( 1_319_286_637L )
2011-10-22T12:30:37Z
Solution using java.time, the modern API:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochSecond(1319286637L);
System.out.println(instant);
}
}
Output:
2011-10-22T12:30:37Z
An Instant represents an instantaneous point on the timeline. The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
You can convert an Instant to other Date-Time types e.g.
import java.time.Instant;
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) {
Instant instant = Instant.ofEpochSecond(1319286637);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
System.out.println(dtf.format(zdt));
}
}
Output:
2011-10-22T18:00:37+05:30[Asia/Kolkata]
10/22/2011 18:00:37
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
Note: 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*. However, for any purpose, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date date = Date.from(instant);
* 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.

server time zone java conversion

Ok, so I've pretty much tried everything. I bet it's something really simple but I can't seem to get a hold of it.
The server sends me the time, which is epoch. However when I put this into a date object it seems to automatically pick up the time zone and it adds +3 to the server time. So if the gmt time is 00.00, it says its 03.00.
I also need to add a timezone of my own. Let's say the epoch time is 00.00 again, it should read 10.00 after I add the timezone.
any help would be much appreciated. Thank you
"It seems to add" - I suspect you're using Date.toString() which does indeed use the local time zone. The Date object itself is effectively in UTC though. Use DateFormat to perform the conversion to a string instead, and you can specify which time zone to use. You may also need to use Calendar - it depends what you're trying to do.
(Alternatively, use Joda Time in the first place, which is a better API. It may be a little bulky for your Android project though. I wouldn't be surprised if there were a "Joda Time lite" project around somewhere for precisely this sort of thing...)
EDIT: Quick sample, although it's not entirely clear what you need...
long millis = getMillisFromServer();
Date date = new Date(millis);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(customTimeZone);
String formatted = format.format(date);
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:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
long millis = 1316391494L;
Instant instant = Instant.ofEpochMilli(millis);
System.out.println(instant);
// The same instant at a specific timezone
ZonedDateTime zdt = instant.atZone(ZoneId.of("Australia/Brisbane"));
System.out.println(zdt);
}
}
Output:
1970-01-16T05:39:51.494Z
1970-01-16T15:39:51.494+10:00[Australia/Brisbane]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
What went wrong with your code?
A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
long millis = 1316391494L;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX[zzzz]", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
System.out.println(strDateUtc);
sdf.setTimeZone(TimeZone.getTimeZone("Australia/Brisbane"));
String strDateBrisbane = sdf.format(date);
System.out.println(strDateBrisbane);
}
}
Output:
1970-01-16T05:39:51.494Z[Coordinated Universal Time]
1970-01-16T15:39:51.494+10:00[Australian Eastern Standard Time]
ONLINE DEMO
* 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.

simple date formatter issue in java

I want to parse date of following type:
2010-07-13T17:27:00.000Z
How can i do it using simple date formatter in java? what format is to be used?
Take a look at the javadocs of SimpleDateFormat.
Create an instance of this class, using the appropriate String in the constructor
Call its parse method, passing in the String in your question
???
Profit!
(You may notice that I'm not actually giving you the format string. This is a "teach a man to fish" answer. If you have problems working out specifically what you'd need to use for a particular section, then feel free to elaborate, stating what you tried and why it didn't work. But right now it sounds like you haven't got to the point of attempting any specific format strings. The Javadocs are reasonably well-written and contain everything you need. Being able to extract information from documentation is a massively important skill for a programmer and I'm not going to rob you of a chance to improve on it.)
The code should look like the following code.
For your date string "2010-07-13T17:27:00.000Z" you may try this format "yyyy-MM-dd'T'hh:mm:ss.S'Z'".
I assume the 'T' and 'Z' in your date string is constant/separator only.
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestMain {
public static void main(String[] args) throws Exception{
String fromDateTime = "2010-12-01 00:01:23";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = null;
date = format.parse(fromDateTime);
//What ever you want to manipulate of this date object
//...
}
}
EDIT: add proper class, method & comment to make it a complete program. Thanks for comment from #Andrzej Doyle.
EDIT: remove throws IOException from the demo program. Thanks for #BalusC.
EDIT: re-read the comment, got the full meaning of #BalusC :)
The date-time string, 2010-07-13T17:27:00.000Z complies with ISO 8601 date-time pattern. In this string, T is a separator for date and time and Z stands for Zulu which specifies UTC (i.e. a timezone offset of +00:00 hours). The format required to parse this date-time string is as follows:
yyyy-MM-dd'T'HH:mm:ss.SSSX
Learn more about the pattern at the documentation page.
Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String args[]) throws ParseException {
String strDateTime = "2010-07-13T17:27:00.000Z";
Instant instant = Instant.parse(strDateTime);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(instant);
System.out.println(zdt);
System.out.println(odt);
// #################Using legacy API####################
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse(strDateTime);
// Default format
System.out.println(date);
// Custom format
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(date));
// #####################################################
}
}
Output:
2010-07-13T17:27:00Z
2010-07-13T17:27Z
2010-07-13T17:27Z
Tue Jul 13 18:27:00 BST 2010
2010-07-13T17:27:00.000Z
Note that the default patterns in modern date-time follow ISO 8601 standard and there you do not need a DateTimeFormatter (the counterpart of SimpleDateFormat in the modern date-time API) explicitly in order to parse an ISO 8601 date-time string. Learn more about the modern date-time API from Trail: Date Time.
Another point important to be mentioned here is the java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.
* 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