I have the number of seconds from 31 Dec 1969 19:00:00 i.e. (EST) and I want to convert the same to a date format.
I have the following code which returns any invalid date. Can anyone point out what seems to be the issue here.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class sample
{
public static void main(String args[])
{
DateFormat df = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("EST"));
Date d1 = new Date(1000*1373604190); //Converting to millisecond
String formattedDate = df.format(d1);
System.out.println(formattedDate); //I'm getting 22/Dec/1969 16:50:55
}
}
How can I solve this.
You are using int literals instead of long in your numbers. By default a integral literal is int unless you specify that is long with L at the end. Try this:
Date d1 = new Date(1000*1373604190L);
(note the L at the end of your literal 1373604190)
tl;dr
Instant.ofEpochSeconds( 1_373_604_190L )
.atZone( ZoneId.of( "America/New_York" ) )
.format( DateTimeFormatter.ofPattern( "dd MMM uuuu HH:mm:ss" , Locale.CANADA ) )
Details
the number of seconds from 31 Dec 1969 19:00:00 i.e. (EST)
Do not think parochially when doing date-time work. Rather than translate values such as the epoch reference moment in and out of your own zone, just think in UTC. Consider UTC to be The One True Time, all others being variations on that theme.
So, always refer to the epoch reference moment as 1970-01-01T00:00:00Z, the first moment of 1970 in UTC, rather than in any other time zone.
(EST)
Also, never use those 3-4 letter abbreviations as time zones. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Those 3-4 letter abbreviation such as EST or IST are not true time zones, not standardized, and not even unique(!).
Using java.time
The modern way to do this work is with the java.time classes.
long secondsSinceEpoch = 1_373_604_190L ;
We convert that to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochSeconds( secondsSinceEpoch ) ;
To see this value through the lens of some wall-clock time, apply a time zone as a ZoneId to get a ZonedDateTime object.
I am guessing that by EST you meant the time zone used by much of the eastern portions of the United States and Canada. I will arbitrarily choose the time zone America/New_York.
ZoneId z = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = instant.atZone( "America/New_York" );
secondsSinceEpoch: 1373604190
instant.toString(): 2013-07-12T04:43:10Z
zdt.toString(): 2013-07-12T00:43:10-04:00[America/New_York]
See live code at IdeOne.com.
Strings
To generate a string, you can either let java.time automatically localize or you can specify an explicit formatting pattern.
Locale locale = Locale.CANADA ;
DateTimeFormatter formatterLocalized = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale );
String outputLocalized = zdt.format( formatterLocalized );
12-Jul-2013 12:43:10 AM
DateTimeFormatter formatterCustom = DateTimeFormatter.ofPattern( "dd MMM uuuu HH:mm:ss" , locale );
String output = zdt.format( formatterCustom );
12 Jul 2013 00:43:10
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import groovy.time.TimeCategory
def startDate = 'Monday, May 11 2015'
def today = new Date().format( 'EEEE, MMM dd yyyy' )
def today1 = quantityService.normalizeAndFormat(today, DatumType.DATE,
Formatters.DATE_IN_WORDS)
def diff = today1.minus(startDate);
The startDate is a string extracted from the database. And is formatted exactly like today1 is formatted above to produce 'Monday, May 11 2015'. I am unable to perform the subtract operation to obtain the value of the variable diff. Can you please guide me on how can I obtain the value of diff in the same format like startDate? Currently, the operation doesn't work probably because startDate is a string and today1 is a date object.
tl;dr
Use modern java.time classes, not the terrible legacy classes. Never use Date or DateFormat or SimpleDateFormat.
Example code in Java syntax:
Period
.between(
LocalDate.parse(
"Monday, May 11 2015" ,
DateTimeFormatter.ofPattern( "EEEE, MMM d uuuu" , Locale.US )
) ,
LocalDate.now( ZoneId.of( "America/Los_Angeles" ) )
)
.toString() ;
P3Y8M18D
Avoid legacy date-time classes
You are using terrible date-time classes that were obsoleted years ago by the java.time classes, with the adoption of JSR 310.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
DateTimeFormatter
Define a formatting pattern to match your input. (Java syntax)
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEEE, MMM d uuuu" , Locale.US ) ;
String input = "Monday, May 11 2015" ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2015-05-11
Elapsed time
To calculate elapsed time as years-months-days, use Period. For days (24-hour chunks of time, not calendar days), hours, and seconds, use Duration.
Period p = Period.between( ld , today ) ;
p.toString(): P3Y8M18D
That string in standard ISO 8601 formats means “three years, eight months, and eighteen days”.
See the above code run live at IdeOne.com.
There is no localization feature in java.time to represent a Period or Duration with words. Instead, you can generate your own string.
String output = p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days" ; // Obviously, you could get fancier by checking for zero or singular values and then adjust the text.
ISO 8601
Avoid exchanging date-time values using localized formats such as that seen in your input. Instead, when exchanging date-time values as text, always use the standard ISO 8601 formats. They were wisely designed to avoid ambiguity. They are easy to parse by machine, and easy to read by humans across cultures.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify any formatting pattern.
For a date-only value, the standard format is YYYY-MM-DD such as 2019-01-23.
LocalDate ld = LocalDate.parse( "2019-01-23" ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I need to convert a Date which is in CST to required time zone. I will get Date as String like "11/5/2018 12:54:20" which is in CST time zone. I have to convert this to a time zone which is passed as a parameter. suppose lets take it as "GMT+0530".
The result for the above date ideally "Nov 06 2018 00:24:20"
I have tried the below code which returned the passed date(11/05/2018 12:54:20) as same instead of(Nov 06 2018 00:24:20) . I have executed this on a system which has IST time zone.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-0600"));
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20").getTime()));
Edit:
Answer:
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ZoneId z = ZoneId.of( "GMT-0600" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
System.out.println(zdt);
ZoneId zKolkata = ZoneId.of( "GMT+0530" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
System.out.println(zdtKolkata);
tl;dr
LocalDateTime // Represent a date and a time-of-day, without offset nor zone. So *not* a moment, *not* a point on the timeline.
.parse(
"11/5/2018 12:54:20" ,
DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) // Define a formatting pattern to match your input string.
) // Returns a `LocalDateTime`.
.atZone( // Assign a time zone, to give meaning to the `LocalDateTime` object, making it a `ZonedDateTime` object.
ZoneId.of( "America/New_York" ) // Define a time zone properly with `Continent/Region` naming, never 2-4 letter pseudo-zones such as CST or IST.
) // Returns a `ZonedDateTime` object.
.withZoneSameInstant( // Adjust from New York time to Kolkata time. Some moment, different wall-clock time.
ZoneId.of( "Asia/Kolkata" )
) // Returns another `ZonedDateTime` object rather than altering (“mutating”) the original, per Immutable Objects pattern.
.toString() // Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
2018-05-11T22:24:20+05:30[Asia/Kolkata]
java.time
You are using terrible old classes, now supplanted by java.time classes.
Parse your input string as a LocalDateTime because it lacks any indication of offset-from-UTC or time zone.
Define a formatting pattern to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ldt.toString(): 2018-05-11T12:54:20
You say this was intended for CST. Did you mean China Standard Time? Or Central Standard Time in North America?
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as CST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
I will assume you meant something like New York time.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2018-05-11T12:54:20-04:00[America/New_York]
And apparently you want to see this same moment through the lens of the wall-clock time used by the people of a different region, a different time zone. By IST did you mean Irish Standard Time? Or India Standard Time? Again, use real time zones not these 2-4 character pseudo-zones.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
zdtKolkata.toString(): 2018-05-11T22:24:20+05:30[Asia/Kolkata]
To see the same moment in UTC, extract a Instant.
Instant instant = zdtKolkata.toInstant() ;
instant.toString(): 2018-05-11T16:54:20Z
All three of these ( zdt, zdtKolkata, instant ) all represent the same moment, the same point on the timeline.
In contrast, the ldt as a LocalDateTime object does not represent a moment, is not a point on the timeline. It held no real meaning until you assigned it a time zone to give it a context. Until assigning that zone, we do not know if meant noon hour in Australia or in Africa, or in America. It could have meant any of about 26-27 hours, the range of time zones around the globe.
ISO 8601
Rather than inventing your own formats for exchanging date-time values as text, use the standard ISO 8601 formats.
The java.time classes conveniently use ISO 8601 formats by default when generating/parsing strings.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You are setting the timezone of sdf twice and not setting timezone of sdf2 and thus getting incorrect results. Also, you don't need to call getTime() when passing object to DateFormat::format().
Here is a fixed version of your code:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
TimeZone cstTimeZone = TimeZone.getTimeZone("CST");
sdf.setTimeZone(cstTimeZone);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20")));
Note that the classes you are using are quite old and since version 8, Java provides new Date and Time APIs.
I need to format a string date with given time zone and return the date object back. I am currently in IST time zone.
So IST is 5 hours and 30 minutes ahead of UTC.
public void getDate(){
String dateStr = "11/25/2016T13:30:00.000";
String dateFormat = "MM/dd/yyyy'T'HH:mm:ss.SSS";
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(date);
}
public static Date formatedStringToDate(final String date, final String dateFormat) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDate = null;
if (date != null) {
try {
parsedDate = sdf.parse(date);
} catch (ParseException e) {
throw e;
}
}
return parsedDate;
}
I get the below out put.
Fri Nov 25 19:00:00 **IST** 2016
The time seems to be change from 5.30 hours but then if its a IST to UCT time converstion, it should be 5.30 hours before 13:30:00 which is 08:00:00?
Also how could I change the highlighted IST part of out put string to show the currect time zone in this case UTC?
When you call toString on a Date (by printing it) you get the default format (because a Date is an object that stores a number of milliseconds, or nanoseconds in Java 9+, since an epoch). To see the result in UTC you need something like,
final DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.FULL);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(sdf.format(date)); // <-- format the Date
tl;dr
LocalDateTime.parse( "2017-11-25T13:30:00.000" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
2017-11-25T13:30+05:30[Asia/Kolkata]
java.time
The modern approach uses the java.time classes that replaced the troublesome old legacy date-time classes.
Parse your input string as a LocalDateTime given the lack of any indicator of zone or offset-from-UTC.
Using standard ISO 8601 format for such strings is preferred. The java.time classes use the standard formats by default when parsing/generating strings.
LocalDateTime ldt = LocalDateTime.parse( "2017-11-25T13:30:00.000" ) ;
ldt.toString(): 2017-11-25T13:30
If you are certain this date-time was intended to represent a moment by the wall-clock time of India, then assign a time zone to produce a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2017-11-25T13:30+05:30[Asia/Kolkata]
You can adjust into another zone for comparison.
ZonedDateTime zdtMontreal = zdt.withZoneSameInstant( ZoneId.of( "America/Montreal") );
zdtMontreal.toString(): 2017-11-25T03:00-05:00[America/Montreal]
To parse/generate strings in other formats such as the one in your Question, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Search Stack Overflow for more info, as these have been covered extensively.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu'T'HH:mm:ss.SSS" , Locale.US ) ;
Use that formatter for parsing.
LocalDateTime ldt = LocalDateTime.parse( "11/25/2016T13:30:00.000" , f ) ;
And for generating.
String output = ldt.format( f ) ; // Generate string.
Consider using ISO 8601 formats instead.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to read the system date in CST time zone using Java. I tried the below code but whenever I use formatter.parse() it is returning time in EST time zone.
private Date getTodayInCST() {
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
String today = formatter.format(currentdate.getTime());
try {
return formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
tl;dr
ZonedDateTime.now(
ZoneId.of( "America/Chicago" )
)
Details
I am trying to read the system date in CST time zone
By “CST”, do you mean Central Standard Time in North America, or China Standard Time?
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique as seen above with CST.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
java.time
You are using troublesome old date-time classes that are now legacy. Supplanted by the java.time classes.
Get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
2018-02-26T05:45:24.213610Z
Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-25T23:45:24.213610-06:00[America/Chicago]
The above strings are in standard ISO 8601 format. The ZonedDateTime class extends that standard wisely to append the name of the zone in square brackets.
If you want to generate String objects in other formats, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
String output = zdt.format( f ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
If you want to set timezone try it this way
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.setTimeZone(TimeZone.getTimeZone("CST"));
System.out.println(format.format(new Date()));
If want to the code to provide the current time considering the daylight saving adjustment from CST to CDT or vice versa ,you can use the
"CST6CDT" timezone. in place of "CST" in SimpleDateFormat.
SimpleDateFormat cstCdtFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
cstCdtFormat.setTimeZone(TimeZone.getTimeZone("CST6CDT"));
System.out.println(cstCdtFormat.format(new Date()));
I am using java.text.DateFormat in order to display the date and time for a user of my application. Below is my code to test the output.
The issue is that the date is being displayed as 1970 (see output below). How can I update this to the current date and time.
Current Output:
1 Jan 1970 01:00:00
Current code:
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateTimeInstance(),
};
for (DateFormat df : formats) {
Log.d("Dateformat", "Date format: " + (df.format(new Date(0))));
}
Alternatively if the above is not possible, I am able to get the current time and date using the following method:
Time now = new Time();
now.setToNow();
String date= now.toString();
Output:
20140722T133458Europe/London(2,202,3600,1,1406032498)
How can I adjust this in order to make it readable for a user?
Just write new Date() instead of new Date(0) in your first snippet. When you write new Date(some number) it makes a date which is that many milliseconds after 1/1/1970 00:00:00Z
Use this -
String S = new SimpleDateFormat("MM/dd/yyyy").format(System.currentTimeMillis());
tl;dr
Instant.now()
.atZone( ZoneId.of( "America/Montreal" ) )
.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
)
Instant
The accepted Answer by Wallace is correct.
But know that you are using troublesome old date-time classes now supplanted by the java.time classes.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now(); // Current moment in UTC.
To generate a String representing that moment formatting according to the ISO 8601 standard, simply call toString.
ZonedDateTime
To view the same moment through the lens of some region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z ); // Adjust from UTC to a specific time zone. Same moment, different wall-clock time.
DateTimeFormatter
For presentation to the user, let java.time automatically localize using the DateTimeFormatter class.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.