Set hours minutes and seconds to 00 in ZonedDateTime or Instant - java

I have a date string in Utc format -
String dateStr = "2017-03-03T13:14:28.666Z";
And I want to convert it to below format in Java date representation in ZonedDateTime.
When ZonedDateTime is printed it should show
String dateStr = "2017-03-03T00:00:00.000Z";
I have tried following code -
String timeZone = "America/Los_Angeles";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZoneId zoneId1 = ZoneId.of(timeZone);
String dateStr = "2017-03-03T13:14:28.666Z";
Instant inst = Instant.parse(dateStr, dtf2);
ZonedDateTime dateTimeInTz = ZonedDateTime.ofInstant(inst, zoneId1);
ZonedDateTime startTime = dateTimeInTz.with(LocalTime.of(0, 0, 0, 0));
ZonedDateTime endTime = dateTimeInTz.with(LocalTime.MAX);
System.out.println("Start:"+startTime+", End:"+endTime);
System.out.println("Start:"+startTime.toString()+", End:"+endTime.toString());
ZonedDateTime nT = ZonedDateTime.of ( LocalDate.parse(dateStr, dtf1) , LocalTime.of (0,0,0,0) , ZoneId.of ( timeZone ) );
System.out.println("Start:"+nT);
Output:
Start:2017-03-03T00:00-08:00[America/Los_Angeles], End:2017-03-03T23:59:59.999999999-08:00[America/Los_Angeles]
Start:2017-03-03T00:00-08:00[America/Los_Angeles], End:2017-03-03T23:59:59.999999999-08:00[America/Los_Angeles]
Start:2017-03-03T00:00-08:00[America/Los_Angeles]
I want the start time to be normalized in ZonedDateTime.
I want to achieve it using java libraries only not any third party library.

tl;dr
You are working too hard.
Instant.parse( "2017-03-03T13:14:28.666Z" )
.truncatedTo( ChronoUnit.DAYS )
.toString()
2017-03-03T00:00.00Z
Details
What does "normalized in ZonedDateTime" mean? Please edit your Question to clarify.
When ZonedDateTime is printed it should show … "2017-03-03T00:00:00.000Z"
What you are asking is a contradiction. A ZonedDateTime has an assigned time zone for when you want to view a moment though the wall-clock time of a particular region. So asking for a ZonedDateTime to generate a string in UTC such as "2017-03-03T00:00:00.000Z" makes no sense. The Z is short for Zulu and means UTC.
Your input string is in standard ISO 8601 format. The java.time classes use these standard formats by default. So no need to specify a formatting pattern, no need for the DateTimeFormatter class.
Parse as an Instant, a point on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.parse( "2017-03-03T13:14:28.666Z" );
If you want midnight in UTC, truncate.
Instant instantMidnightUtc = instant.truncatedTo( ChronoUnit.DAYS );
instantMidnightUtc.toString(): 2017-03-03T00:00.00Z
No need for the ZonedDateTime class.
If you want to work with a date-only without any time-of-day and without a time zone, use the LocalDate class.
By the way, do not assume the first moment of the day is always 00:00:00. That is true for UTC. But various time zones may have anomalies such as Daylight Saving Time (DST) where the day may start at another time-of-day such as 01:00:00.
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.

String timeZone = "America/Los_Angeles";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZoneId zoneId1 = ZoneId.of(timeZone);
String dateStr = "2017-03-03T13:14:28.666Z";
Instant inst = Instant.parse(dateStr, dtf2);
ZonedDateTime dateTimeInTz = ZonedDateTime.ofInstant(inst, zoneId1);
ZonedDateTime startTime = dateTimeInTz.with(LocalTime.of(0, 0, 0, 0));
ZonedDateTime endTime = dateTimeInTz.with(LocalTime.MAX);
String strStart = (startTime.toString().split("T"))[0] + "T00:00:00.000Z";
String strEnd = (endTime.toString().split("T"))[0] + "T00:00:00.000Z";
System.out.println("Start:"+strStart +", End:"+strEnd );
EDIT new method :
TimeZone timeZone = TimeZone.getTimeZone("Europe/Copenhagen");
Calendar cal = Calendar.getInstance(timeZone);
Calendar defaut = new GregorianCalendar( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),0,0,0);
You juste need to get all your necessary fields. With, for example, a dateFormat.
Hope it will help you

You can simply do:
DateUtils.truncate(yourDate, Calendar.DAY_OF_MONTH);
Hope this will help you

Related

Java date parsing not working for ET timezone while working for IST

I am trying to parse the String to date. String having date format as
"dd-MMM-yyyy Z" and String having value "12-DEC-2018 ET". Its giving the error
java.text.ParseException: Unparseable date: "12-DEC-2018 ET".
The same code is working for String having value "12-DEC-2018 IST".
below is the code snippet:
public static void main(String[] args) throws ParseException {
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
SimpleDateFormat sdfmt1 = new SimpleDateFormat("dd-MMM-yyyy Z");
SimpleDateFormat sdfmt2= new SimpleDateFormat("dd/MM/yyyy");
Date dDate = sdfmt1.parse( dateInputIST );
String strOutput = sdfmt2.format( dDate );
System.out.println(strOutput);
Date etDate = sdfmt1.parse(dateInputET);
strOutput = sdfmt2.format(etDate);
System.out.println(strOutput);
}
Could someone please help. I needed to parse the time in any timezone.
Thanks,
Navin
Change
String dateInputET ="12-DEC-2018 ET";
to
String dateInputET ="12-DEC-2018 EDT";
'ET' is not a recognized time zone.
Pseudo-zones
ET, EST, and IST are not actually time zones. Those 2-4 letter pseudo-zones are not standardized and are not even unique! For example, IST can mean India Standard Time, Ireland Standard Time, Iceland Standard Time, and more.
Real time zone names take the format of Continent/Region such as Africa/Tunis.
Date & zone, separately
Date with time zone has no real meaning.
Handle the date as a LocalDate object.
String input = "12-DEC-2018"
DayeTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Handle your desired time zone separately, as a ZoneId object.
ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
To combine, determine the first moment of the day.
ZonedDateTime zdtNewYork = ld.atStartOfDay( z ) ;
Generate text representing that moment in standard ISO 8601 format extended to append the name of the time zone in square brackets.
To see that same moment in UTC, extract a Instant.
Instant instant = zdtNewYork.toInstant() ;
Adjust into another zone.
ZonedDateTime zdtKolkata = instant.atZone( ZoneId.of( "Asia/Kolkata" ) ) ;
To focus on the date only, get a LocalDate for the day of that same moment when viewed through the lens of the wall-clock time used in India.
LocalDate ldKolkata = zdtKolkata.toLocalDate() ;
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.
java.time
DateTimeFormatter dateZoneFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uuuu v")
.toFormatter(Locale.ENGLISH);
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
TemporalAccessor parsed = dateZoneFormatter.parse(dateInputIST);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
parsed = dateZoneFormatter.parse(dateInputET);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
On my computer the output from this snippet was:
Date: 2018-12-12 Time zone: Atlantic/Reykjavik
Date: 2018-12-12 Time zone: America/New_York
Format pattern letter v is for the generic time-zone name, that is, the name that is the same all year regardless of summer time (DST), for example Eastern Time or short ET.
If you want to control the interpretation of ambiguous time zone abbreviations (of which there are a lot), you may use the two-arg appendGenericZoneText​(TextStyle, Set<ZoneId>) where the second argument contains the preferred zones. Still better if there is a way for you to avoid relying on time zone abbreviations altogether since, as I said, they are very often ambiguous.
I am not sure what sense a date with a time zone makes, though.
As an additional point, always specify locale for your formatters so they will also work if the default locale is changed or one day your program runs in a JVM with a different default locale.
Avoid SimpleDateFormat and Date
I don’t think SimpleDateFormat will be able to parse your string. It’s just the same since that class is already long outdated and is renowned for being troublesome, so you should never want to use it anyway.

Adding time in hours to a date object in java? [duplicate]

This question already has answers here:
Adding n hours to a date in Java?
(16 answers)
Closed 4 years ago.
How do i add hours to a date object. Below is my code:
String dateStart = timeStamp;
String dateStop = valueCon;
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(datestop);
I want to add 4 hours to d2 date object. How do i achieve it?
I tried to use :
Date modd1= new Date(d2+TimeUnit.MINUTES.toHours(240));
But it accepts only long object for adding. Thus failed.
Please support to solve this.Thanks in advance.
like others, i'd recommend using java.time if that's an option. the APIs are more consistent, and do a better job of catering to these types of operations.
however, to answer your question as-is... one option is to adjust the millisecond form of the Date instance by using get/setTime() as follows:
#Test
public void adjustTime() {
final Date date = new Date();
System.out.println("## Before adding four hours: " + date);
date.setTime(date.getTime() + TimeUnit.HOURS.toMillis(4));
System.out.println("## After adding four hours: " + date);
}
hope that helps!
If you are using java.time it can be more helpful :
LocalDateTime dateStart = LocalDateTime.now();
LocalDateTime dateStop = dateStart.plusHours(4);
To format the date you can use :
String d1 = dateStart.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
String d2 = dateStop.format(DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));
Well there are several ways to do
Using Calendar class
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(anyDateObject); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 4); // adds four hour
Date date = cal.getTime(); // returns new date object
If you are using ApacheCOmmon Lang
Date newDate = DateUtils.addHours(oldDate, 3);
If you are using Joda-time
DateTime dt = new DateTime();
DateTime added = dt.plusHours(4);
and if you are using Java 8 best would be LocalDateTime
LocalDateTime startDate = LocalDateTime.now();
LocalDateTime stopdate = startDate.plusHours(4);
tl;dr
Never use Date or SimpleDateFormat classes.
Use only modern java.time classes.
Example code:
LocalDateTime.parse( // Parsing input string to an object without concept of zone or offset.
"18/01/23 12:34:56" , // Input lacking indicator of zone/offset.
DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) // Define formatting pattern matching your input.
)
.plusHours( 4 ) // Add four hours. Generating a new `LocalDateTime` object, per immutable objects pattern.
.toString() // Generate a String in standard ISO 8601 format.
2018-01-23T16:34:56
java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Never use Date, Calendar, SimpleDateFormat.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uu/MM/dd HH:mm:ss" ) ;
Unzoned
Apparently your input lacks an indicator of time zone or offset-from-UTC. So parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "18/01/23 12:34:56" ) ;
ldt.toString(): 2018-01-23T12:34:56
A LocalDateTime has no concept of time zone or offset-from-UTC. So it does not represent an actual moment, and is not a point on the timeline. A LocalDateTime is only a rough idea about potential moments along a range of about 26-27 hours.
Zoned
If you know for certain the input data was intended to represent a moment in a particular zone, apply a ZoneId to produce a ZonedDateTime. A ZonedDateTime does represent an actual moment, a point on the timeline.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Determining an actual moment.
zdt.toString(): 2018-01-23T12:34:56+01:00[Africa/Tunis]
To see the same moment in UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
Math
Represent a span of time unattached to the timeline as a Duration object.
Duration d = Duration.ofHours( 4 ) ; // Four hours, as an object.
Add to your LocalDateTime, if not using time zones.
LocalDateTime ldtLater = ldt.plus( d ) ;
If using zoned values, add to your ZonedDateTime.
ZonedDateTime zdtLater = zdt.plus( d ) ;
Those classes also offer shortcut methods, if you wish.
ZonedDateTime zdtLater = zdt.plusHours( 4 ) ; // Alternative to using `Duration` object.
One benefit of using a Duration rather than the shortcut methods is having an object that can be named.
Duration halfShiftLater = Duration.ofHours( 4 ) ;
…
ZonedDateTime zdtLater = zdt.plus( halfShiftLater ) ;
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, 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 (<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 can do something like
Calendar c = Calendar.getInstance();
c.setTimeInMillis(d2.getTime());
c.add(Calendar.HOUR_OF_DAY, 4);
d2 = c.getTime();
I recommend you using JDK8 time API or joda-time if you can.
Old java api for date is so bad!
In your case, you can:
//commons-lang3
Date oldDate = new Date();
Date newDate = DateUtils.addHours(oldDate, 1);
OR
convert date to timestamp, add some mills and convert timestamp back to date

Convert Time Zone from a String to a particular Time Zone taking DST into consideration of target Time Zone

I am trying to convert a date string in format "yyyyMMddHHmmss" to a date string for another Time Zone "America/Sao_Paulo" taking DST into consideration for America/Sao_Paulo ( which start on 16-oct-2016 ).
I am using TimeZone class as
TimeZone represents a time zone offset, and also figures out daylight
savings.
import java.util.TimeZone;
import java.text.*;
import java.util.Date;;
public class TimeZoneConversion {
public static void main(String[] args)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
try
{
String inputdate = "20161016052355";
Date t = sdf.parse(inputdate);
System.out.println(t);
}
catch(ParseException e)
{
}
}
}
Output for the above is shown in IST
Sun Oct 16 12:53:55 IST 2016
How can i convert the the time string with input "yyyyMMddHHmmss" to a time string in "America/Sao_Paulo" Time Zone with DST in output ?
You are simply printing it in a timezone where it is not daylight savings time on that date - printing a Date prints it in the JVM's default timezone.
For instance, replacing System.out.println(t) with:
SimpleDateFormat out = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss zzzz");
out.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(out.format(t));
prints:
2016/10/16 05:23:55 Brasilia Summer Time
Ideone demo
java.time
You are using troublesome old date-time classes, now supplanted by the java.time classes.
Your input lacks any offset-from-UTC or time zone info. So we parse as a LocalDateTime, meaning any locality.
String input = "20161016052355";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2016-10-16T05:23:55
A LocalDateTime is not a moment, not a point on the timeline. To give it real meaning, you must provide the intended time zone (or offset).
ZoneId z = ZoneId.of( "America/Sao_Paulo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2016-10-16T05:23:55-02:00[America/Sao_Paulo]
To see the same moment as UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
instant.toString(): 2016-10-16T07:23:55Z
See this code run live at IdeOne.com.
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, 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
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.
Please check with this...
please replace your specific time_zone
string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt =
DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "yyyyMMddHHmmss", null);
This worked for me
try
{
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddhhmmss");
f.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date time = f.parse("20161015113634");
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
formatter.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(formatter.format(time));
}
catch (ParseException e){
}
Input : 20161015113634 (Time which is not in DST)
Output: 20161015030634 (Converted time for SaoPaulo)
Input : 20161016113634 (Time in DST)
Output: 20161016040634 (Converted time for SaoPaulo with DST Offset)

How to Format ISO-8601 in Java

I am trying to change from standard ISO 8601 format 2014-09-11T21:28:29.429209Z into a nice MMM d yyyy hh:mm z format, however my current code is failing.
public void setCreatedAt( String dateTime ) {
LocalDate newDateTime = LocalDate.parse(dateTime);
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a z");
createdAt = newDateTime.format(format);
}
catch (Exception e) {
}
}
I am receiving the time and date from an api.
A java.time.LocalDate is "a date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03" so there is not enough information there. Use java.time.ZonedDateTime instead.
Also, swallowing exceptions like that makes it much harder to troubleshoot. When you don't intend to handle an exception either don't catch it at all, catch and re-throw it wrapped in a RuntimeException or at the very least log it (e.printStackTrace() or similar) .
tl;dr
Instant.parse( "2014-09-11T21:28:29.429209Z" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.format( DateTimeFormatter.ofPattern("MMM d uuuu hh:mm a z" , Locale.US ) )
See this code run live at IdeOne.com.
Details
The Answer by Jakber will work technically but is misleading.
ZonedDateTime is for time zones
A ZonedDateTime is meant to have an assigned time zone such as America/Montreal or Pacific/Auckland.
But this input string lacks a time zone. The Z on the end is short for Zulu and means UTC, or in other words, an offset-from-UTC of zero hours, +00:00.
A time zone is a historical collection of offsets for a particular region with rules for upcoming changes to the offset for anomalies such as Daylight Saving Time (DST).
Instant
The input string is better parsed as an Instant which represents a moment on the timeline always in UTC. This class directly parses such strings in that particular standard ISO 8601 format, so no need for formatting pattern.
Instant instant = Instant.parse( "2014-09-11T21:28:29.429209Z" );
Adjust into time zone
You can adjust into a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generating string
To generate a string in the same format as input, simply call Instant::toString().
String output = instant.toString() ;
For your custom format using the wall-clock time of a region, use DateTimeFormatter with your custom formatting pattern. And your ZonedDateTime. As a good habit, always specify the desired Locale used for the human language in translation and cultural norms in formatting.
DateTimeFormatter f = DateTimeFormatter.ofPattern("MMM d uuuu hh:mm a z" , Locale.US );
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.
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, 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 (<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.
public void setCreatedAt(String dateTime) {
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
SimpleDateFormat sdfTarget = new SimpleDateFormat("MMM d yyyy hh:mm a z", Locale.getDefault());
try {
Date date = sdfSource.parse(dateTime);
String createdAt = sdfTarget.format(date);
Log.e(TAG, "setCreatedAt: createdAt " + createdAt);
} catch (ParseException e) {
e.printStackTrace();
}
}

Setting DateFormat to current date and time

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.

Categories

Resources