I have a UTC date in string
String utcDate = "2014-03-05 07:09:07.0";
I want to convert it to local date string of format DD-MMM-YYYY hh:mm a
eg: 5-Mar-2014 12:39 PM from UTC date 2014-03-05 07:09:07.0
How this can be achieved using simple java or joda API
Very easy to achieve with default functionality. I hope the local data is for display only.
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = parser.parse(utcDate);
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM-yyyy hh:mm a");
System.out.println(formatter.format(parsed));
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
If you use the ISO 8601 format of strings, you can pass the string directly to a Joda-Time DateTime constructor. Your input string is close, but the space in the middle should be a T.
Some example code using the Joda-Time 2.3 library.
String input = "2014-03-05 07:09:07.0";
String inputModified = input.replace( " ", "T" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeUtc = new DateTime( inputModified, DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeUTC.toZone( timeZone );
String outputFrance = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( dateTimeParis );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-MMM-yyyy hh:mm a" ).withLocale( Locale.US );
String outputParisCustom = formatter.print( dateTimeParis );
Below code will help you to convert your UTC to IST or any other timezone. You need to pay attention to the timezone that you want to use with SimpleDateFormat.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class ConvertTimeZone {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-03-05 07:09:07");
System.out.println("time in UTC " +sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Time in IST is " + sdf.format(date));
}
}
Related
This question already has answers here:
How to set time zone of a java.util.Date?
(12 answers)
Closed 7 months ago.
I want to change the time zone of given date. I use this code, but i dont have the good result.
My input is "2020-06-16 14:00:00" time in Europe/Paris, and I wnat to change it to UTC, that means I want to get "2020-06-16 12:00:00", but I get initial result "2020-06-16 14:00:00".
try {
// Calendar calParis = Calendar.getInstance();
String heure = "1400";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-16");
String hour = heure.substring(0, heure.length() - 2);
String minute = heure.substring(heure.length() - 2);
Calendar cal = Calendar.getInstance();
String datenew = "2020-06-16" + " " + hour + ":" + minute + ":00";
SimpleDateFormat sdfDatenew = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date thisDate = sdfDatenew.parse(datenew);
cal.setTime(thisDate);
cal.setTimeZone(TimeZone.getTimeZone("Europe/UTC"));
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
String dateISO = null;
dateISO = sdfDate.format(cal.getTime());
System.out.println("Time in ISO: " + dateISO);
} catch (Exception ex) {
}
Here you go:
This way you can get your dates and time in Java-7 format.
public static void main(String[] args) throws ParseException {
String heure = "1400";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-16");
String hour = heure.substring(0, heure.length() - 2);
String minute = heure.substring(heure.length() - 2);
String datenew = "2020-06-16" + " " + hour + ":" + minute + ":00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Calendar calendar = Calendar.getInstance();
Date thisDate = sdf.parse(datenew);
calendar.setTime(thisDate);
sdf.setTimeZone(TimeZone.getTimeZone("PDT"));
System.out.println(sdf.format(calendar.getTime())); // prints 2020-06-16 12:00:00
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(calendar.getTime())); // prints 2020-06-16 14:00:00
}
tl;dr
LocalDateTime
.parse(
"2020-06-16 14:00:00"
.replace( " " , "T" )
)
.atZone(
ZoneId.of( "Europe/Paris" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
.format(
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )
)
See this code run live at IdeOne.com.
2020-06-16 12:00:00
java.time
The modern solution uses java.time classes.
Your input string lacks a time zone or offset. So parse as a LocalDateTime object.
LocalDateTime ldt = LocalDateTime.parse( "2020-06-16 14:00:00".replace( " " , "T" ) ) ;
You say with certainty that this string represents a moment as seen in Paris France time zone.
ZoneId zParis = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = ldt.atZone( zParis ) ;
Adjust from there to your target time zone. You happen to want UTC, so just extract an Instant.
Instant instant = zdt.toInstant() ;
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*, released in March 2014 as part of Java SE 8 standard library.
The answer by Basil Bourque is correct but I would not use String replacement when DateTimeFormatter is capable enough to address this and much more.
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) {
String input = "2020-06-16 14:00:00";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(input, dtfInput);
ZonedDateTime zdtParis = ldt.atZone(ZoneId.of("Europe/Paris"));
ZonedDateTime zdtUtc = zdtParis.withZoneSameInstant(ZoneId.of("Etc/UTC"));
// Default format
System.out.println(zdtUtc);
// Custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String output = dtfOutput.format(zdtUtc);
System.out.println(output);
}
}
Output:
2020-06-16T12:00Z[Etc/UTC]
2020-06-16 12:00:00
ONLINE DEMO
All in a single statement:
System.out.println(
LocalDateTime
.parse("2020-06-16 14:00:00", DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH))
.atZone(ZoneId.of("Europe/Paris"))
.withZoneSameInstant(ZoneId.of("Etc/UTC"))
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH))
);
ONLINE DEMO
Some important notes:
You can use a single pattern, uuuu-MM-dd HH:mm:ss for both of your input and output strings but I prefer using u-M-d H:m:s for parsing because uuuu-MM-dd HH:mm:ss will fail if you have a year in two digits, a month in single digit, a day-of-month in single digit etc. For parsing, a single u can cater to both, two-digit and four-digit year representation. Similarly, a single M can cater to both one-digit and two-digit month. Similar is the case with other symbols.
Here, you can use y instead of u but I prefer u to y.
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.
I try to parse a date from a string but when I print it, it shows a bad date. My code:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String args[]) {
String some_date = "2017-12-31";
Calendar cal_aux = GregorianCalendar.getInstance();
System.out.println("set calendar: " + Integer.parseInt(some_date.substring(0, 4))
+ Integer.parseInt(some_date.substring(5, 7))
+ Integer.parseInt(some_date.substring(8, 10)));
cal_aux.set(Integer.parseInt(some_date.substring(0, 4)),
Integer.parseInt(some_date.substring(5, 7)),
Integer.parseInt(some_date.substring(8, 10)));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("sdf calendar: " + sdf.format(cal_aux.getTime()));
}
}
Console output:
set calendar: 20171231
sdf calendar: 2018-01-31 12:51:02
Why when I use the simple date format I'm getting 2018 instead of 2017?
Avoid the legacy date-time classes now supplanted by java.time classes. The problematic legacy classes have many design faults. One such fault is counting months as 0-11 rather than 1-12. This crazy counting is breaking your code.
Do not manipulate date-time values as strings. Use objects.
For that date-only value use LocalDate.
LocalDate ld = LocalDate.parse( "2017-12-31" ) ; // Or LocalDate.now() for today's date.
Generate a String by using a DateTimeFormatter.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;
20171231
Assign a time-of-day if desired.
LocalTime lt = LocalTime.of( 6 , 15 ) ;
LocalDateTime ltd = LocalDateTime.of( ld , lt ) ;
Apply a time zone if you want an actual moment, a specific point on the timeline.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
First, you set wrong date because the month range is 0-11. When you set 12 in month field, is january 2018 instead december 2017.
Second, you can simplify your program parsing the input string to formatted date and parsing this date to output formatted string. Here is an example:
String input = "20171231";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
System.out.println(outputFormat.format(inputFormat.parse(input)));
} catch (ParseException e) {
// Log error
}
I am trying to add 17 days to 10-APR-2014 and convert the date to dd-MMM-yyyy format, but I am getting Sun Apr 27 00:00:00 GMT+05:30 2014.
Here is my code:
import java.util.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 17);
String output = sdf.format(c.getTime());
System.out.println(output);
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").parse(output));
}
}
How can I make the output be 27-Apr-2014?
You are printing a Date parsed from a String formatted from the calendar date.
Instead, print the formatted calendar date:
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").format(c.getTime()));
If displaying and using the dates is disjunct, do this:
Date date; // from Calendar or wherever
String str = new SimpleDateFormat("dd-MMM-yyyy").format(date));
// display str
Then when you want to do something with a selected date:
String selection;
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse(selection));
// do something with date
The answer by Bohemian is correct. Here I present an alternative solution.
Avoid j.u.Date
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Date-Only
If you need only a date, without any time component, both Joda-Time and java.time offer a LocalDate class.
Time Zone
Even for a date-only, you still need a time zone to get "today". At any moment the date may vary ±1 depending on your location on the globe. If you do not specify a time zone, the JVM's default time zone will be applied.
Example Code
Here is some example code in Joda-Time 2.3.
Determine "today" based on some time zone. Add seventeen days.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
LocalDate today = new LocalDate( timeZone );
LocalDate seventeenDaysLater = today.plusDays( 17 );
Generate a String representation of the date-time value…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MMM-yyyy" );
String output = formatter.print( seventeenDaysLater );
Dump to console…
System.out.println( "today: " + today );
System.out.println( "seventeenDaysLater: " + seventeenDaysLater );
System.out.println( "output: " + output );
When run…
today: 2014-04-21
seventeenDaysLater: 2014-05-08
output: 08-May-2014
I have a Date field in Java in IST Time. I want to convert the same to EST Time and the output should be as a Date Type only. I am able to accomplish the same using the below piece of code:-
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date date = new Date();
DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String estTime = timeFormat.format(date);
date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(estTime);
The problem with the above piece of code is that though the date is converted in EST Time, the Time Zone is still showing as IST and not EST. The rest of the date is converted perfectly fine. Is there any way to explicitly set the time Zone To EST in the Date Field.Any help regarding this will be highly appreciated.
-Subhadeep
The Date class is time-zone agnostic. Basically, it is always based on GMT although when it is printed it uses the current system time zone to adjust it.
However, Calendar is time-zone specific. See Calendar.setTimeZone().
Consider:
Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("America/New_York"));
cal.setTime(new Date());
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using java.time, the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
ZonedDateTime zdtIndia = instant.atZone(ZoneId.of("Asia/Calcutta"));
ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtIndia);
System.out.println(zdtNewYork);
}
}
Output:
2021-05-19T21:08:54.241341Z
2021-05-20T02:38:54.241341+05:30[Asia/Calcutta]
2021-05-19T17:08:54.241341-04:00[America/New_York]
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).
Learn more about java.time, the modern date-time API* from Trail: Date Time.
Solution using legacy API:
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.
Demo:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS[zzzzz]");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
String dtIndia = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String dtNewYork = sdf.format(date);
System.out.println(dtIndia);
System.out.println(dtNewYork);
}
}
Output:
Wed May 19 22:16:08 BST 2021
2021-05-20T02:46:08.024[India Standard Time]
2021-05-19T17:16:08.024[Eastern Daylight 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.
Should you add z for time-zone pattern in your SimpleDateFormat pattern?
So, it should be DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"). I changed your code like this:
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date date = new Date();
System.out.println(dateTimeFormat.format(date)); // this print IST Timezone
DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String estTime = timeFormat.format(date);
date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z", Locale.ENGLISH).parse(estTime);
System.out.println(timeFormat.format(date)); // this print EDT Timezone currently (on March)
}
In last print statement, current date format is printed with EDT Timezone (Eastern Daylight Time). Maybe because of this.
The correct answer by John B explains that java.util.Date seems to have a time zone but does not. Its toString method applies your JVM's default time zone when generating the string representation.
That is one of many reasons to avoid java.util.Date and .Calendar classes bundled with Java. Avoid them. Instead use either Joda-Time or the java.time package built into Java 8 (inspired by Joda-Time, defined by JSR 310).
Here is some example code in Joda-Time 2.3.
String input = "01/02/2014 12:34:56";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" );
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = formatterInput.withZone( timeZoneIndia ).parseDateTime( input );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime dateTimeNewYork = dateTimeIndia.withZone( timeZoneNewYork );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeNewYork: " + dateTimeNewYork );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 01/02/2014 12:34:56
dateTimeIndia: 2014-01-02T12:34:56.000+05:30
dateTimeNewYork: 2014-01-02T02:04:56.000-05:00
dateTimeUtc: 2014-01-02T07:04:56.000Z
I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.
DateFormat inFm = new SimpleDateFormat("d-MMM-y");
DateFormat outFm = new SimpleDateFormat("d-M-yyyy");
Date date = inFm.parse("14-Dec-2010");
String output = outFm.format(date);
Generally, you should use a datetime type like Date internally, then transform to String at output time.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
/**
* #param args
*/
public static void main(String[] args) {
Date date = new Date("14-Dec-2010"); //deprecated. change it to your needs
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(date));
}
}
I think this SQL convert should work
SELECT CONVERT(datetime,'14-Dec-2010',105)
DateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date= format.parse("14-Dec-2010");
This is how you will get Date Object now you can print it in any format.
Note: month starts from 0 , so for Dec it would be 11
Here is working IDE One demo
Document
Avoid using the troublesome old date-time classes bundled with the earliest versions of Java. They are poorly designed and confusing.
java.time
The old classes are supplanted by the java.time framework.
For a date-only value without time of day and without time zone use LocalDate class.
Parse the String input using DateTimeFormatter.
String input = "14-Dec-2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
To generate a String in another format, define another formatter.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
String output = localDate.format( formatter2 );
Better yet, let DateTimeFormatter automatically localize.
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
String output = localDate.format( f ); // Generates String in a localized format.
SQL
For SQL just pass objects, do not use strings. Pass LocalDate via setObject on a PreparedStatement if your JDBC driver complies with the JDBC 4.2 spec.
myPrepStmt.setObject( localDate );
If not, fall back to the old java.sql.Date class by using new conversion methods added to the old classes.
java.sql.Date sqlDate = java.sql.Date.from( localDate );
myPrepStmt.setDate( sqlDate );