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

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

Related

Add hours and minutes to a Date object [duplicate]

This question already has answers here:
How to combine date and time into a single object?
(3 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Closed 4 years ago.
I have a small gui which have a datepicker and a textbox where I enter a time (HH:mm).
I want to create a method whish takes the Date from the datepicker and adds the time (HH:mm) to the datepicker-date and then returns the Date so I can save it in a database.
I want to have the final date in this format "yyyy-MM-dd HH:mm"
This is what I have tried:
public Date getCalibrationDate(){
String time = getTime();
int hours = Integer.parseInt(time.substring(0,2));
int minutes = Integer.parseInt(time.substring(2,4));
Date date = java.sql.Date.valueOf(kalibreringsdatum.getValue());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE,minutes);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateAsString = sdf.format(calendar.getTime());
Date dateTime = null;
try {
dateTime = sdf.parse(dateAsString);
} catch (ParseException e) {
System.out.println("Could not parse date");
e.printStackTrace();
}
return dateTime;
}
But it returns the date in this way: Tue Dec 11 11:22:00 CET 2018.
What am I doing wrong and how can I simplify the method?
tl;dr
For database column of type TIMESTAMP WITHOUT TIME ZONE.
myPreparedStatement // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject( // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
… , // Fill-in to indicate which placeholder in SQL statement.
LocalDateTime.of( // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
LocalDate.parse( "2018-01-23" ) , // Parse the date-only value.
LocalTime.parse( "21:54" ) // Parse the time-of-day.
) // Returns a `LocalDateTime` object.
)
For database column of type TIMESTAMP WITH TIME ZONE.
myPreparedStatement // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject( // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
… , // Fill-in to indicate which placeholder in SQL statement.
LocalDateTime.of( // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
LocalDate.parse( "2018-01-23" ) , // Parse the date-only value.
LocalTime.parse( "21:54" ) // Parse the time-of-day.
) // Returns a `LocalDateTime` object.
.atZone( // Assign a time zone to make a moment.
ZoneId.of( "Pacific/Auckland" ) // Real time zones have a proper name in `Continent/Region` format. Never use 2-4 letter pseudo-zones such as `PDT`, `IST`, `CST`, etc.
) // Returns a `ZonedDateTime` object.
.toOffsetDateTime() // Strip out the time zone, leaving only a mere offset-from-UTC (a number of hours-minutes-seconds). Returns a `OffsetDateTime` object.
.withOffsetSameInstant( // Adjust the offset-from-UTC to UTC itself (an offset of zero). Same moment, different wall-clock time.
ZoneOffset.UTC
) // Returns another `OffsetDateTime` object.
)
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible old legacy classes (Calendar, Date, SimpleDateFormat, etc.).
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
The common SQL format for a date-only value in text is YYYY-MM-DD. This is also the format defined by the ISO 8601 standard. The java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-01-23" ) ;
Similar for a string in format of HH:MM for hours and minutes of a time-of-day.
LocalTime lt = LocalTime.parse( "21:54" ) ;
Combine the date with the time.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
ldt.toString(): 2018-01-23T21:54
Be aware that a LocalDateTime, purposely lacking any concept of time zone or offset-from-UTC, is not a moment, is not a point on the timeline. As such, it is only appropriate to save to a database in a column of a data type akin to the SQL-standard TIMESTAMP WITHOUT TIME ZONE.
JDBC 4.2
As of JDBC 4.2, we can directly exchange java.time objects with the database via setObject & getObject.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
ZonedDateTime
If you want to work with moments, actual points on the timeline, use the appropriate Java classes (Instant, OffsetDateTime, ZonedDateTime).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
OffsetDateTime
Now we have a moment at hand. Usually best to focus on UTC when moving dates around such as transferring to a database.
OffsetDateTime odtUtc = zdt.toOffsetDateTime().withOffset( ZoneOffset.UTC ) ;
Send to database.
myPreparedStatement.setObject( … , odtUtc ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
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 can use SimpleDateFormat to get what you want:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateAndTime {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
System.out.println(sdf.format(new Date()))
}
}

How to convert UTC Date String and remove the T and Z in Java?

Am using Java 1.7.
Trying to convert:
2018-05-23T23:18:31.000Z
into
2018-05-23 23:18:31
DateUtils class:
public class DateUtils {
public static String convertToNewFormat(String dateStr) throws ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
sdf.setTimeZone(utc);
Date convertedDate = sdf.parse(dateStr);
return convertedDate.toString();
}
}
When trying to use it:
String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z");
System.out.println(convertedDate);
Get the following exception:
Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)
What am I possibly doing wrong?
Is there an easier way to do is (e.g. Apache Commons lib)?
tl;dr
Instant.parse( "2018-05-23T23:18:31.000Z" ) // Parse this String in standard ISO 8601 format as a `Instant`, a point on the timeline in UTC. The `Z` means UTC.
.atOffset( ZoneOffset.UTC ) // Change from `Instant` to the more flexible `OffsetDateTime`.
.format( // Generate a String representing the value of this `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Specify a formatting pattern as desired.
) // Returns a `String` object.
2018-05-23 23:18:31
ISO 8601
Your input string is in standard ISO 8601 format.
The java.time classes use these standard formats by default when parsing/generating strings.
The T separates the year-month-day portion from the hour-minute-second. The Z is pronounced Zulu and means UTC.
java.time
You are using troublesome old date-time classes that were supplanted years ago by the java.time classes. The Apache DateUtils is also no longer needed, as you will find its functionality in java.time as well.
Parse that input string as 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).
String input = "2018-05-23T23:18:31.000Z" ;
Instant instant = Instant.parse( input ) ;
To generate a string in another format, we need a more flexible object. The Instant class is meant to be a basic building block. Lets convert it to a OffsetDateTime`, using UTC itself as the specified offset-from-UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
Define a formatting pattern to match your desired output.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = odt.format( f ) ;
Tip: Consider using DateTimeFormatter::ofLocalized… methods to automatically localize the String generation per some Locale rather than hard-coding a formatting pattern.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Try this. You have to use one pattern for parsing and another for formatting.
public static String convertToNewFormat(String dateStr) throws ParseException {
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(utc);
Date convertedDate = sourceFormat.parse(dateStr);
return destFormat.format(convertedDate);
}
For others without Java 1.7 Restrictions:
Since Java 1.8 you can do it using LocalDateTime and ZonedDateTime from the package java.time
public static void main(String[] args) {
String sourceDateTime = "2018-05-23T23:18:31.000Z";
DateTimeFormatter sourceFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(sourceDateTime, sourceFormat);
String formatedDateTime = dateTime.atZone(ZoneId.of("UTC")).format(targetFormat);
System.out.println(formatedDateTime);
}
EDIT: (see Comments)
Quote from the Oracle Java documentation of LocalDateTime:
LocalDateTime is an immutable date-time object that represents a
date-time, often viewed as year-month-day-hour-minute-second. Other
date and time fields, such as day-of-year, day-of-week and
week-of-year, can also be accessed. Time is represented to nanosecond
precision. For example, the value "2nd October 2007 at
13:45.30.123456789" can be stored in a LocalDateTime.
This class does not store or represent a time-zone. Instead, it is a
description of the date, as used for birthdays, combined with the
local time as seen on a wall clock. It cannot represent an instant on
the time-line without additional information such as an offset or
time-zone.
the OP is asking to JUST parsing an Input String to a date-time (as year-month-day-hour-minute-second) and the Documentation says
LocalDateTime ... represents a date-time, often viewed as
year-month-day-hour-minute-second
so no important information are lost here. And the part dateTime.atZone(ZoneId.of("UTC")) returns a ZonedDateTime so the ZimeZone is handled at this point again if the user needs to work with the timezone ...etc.
so don't try to force users to use the "One and Only" solution you present in your answer.
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:
ZonedDateTime.parse("2018-05-23T23:18:31.000Z")
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH));
ONLINE DEMO
Note that you do not need a custom DateTimeFormatter to parse the date-time string, 2018-05-23T23:18:31.000Z as it is already in the default pattern used by ZonedDateTime. The modern date-time API is based on ISO 8601.
Learn more about the modern Date-Time API from Trail: Date Time.
Some helpful answers using java.time API:
'Z' is not the same as Z.
Never use SimpleDateFormat or DateTimeFormatter without a Locale.
I prefer u to y with a DateTimeFormatter.
For the sake of completeness
For the sake of completeness, given below is a solution using the legacy date-time API:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateTime = parser.parse("2018-05-23T23:18:31.000Z");
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
formatter.setTimeZone(parser.getTimeZone());
String formattedDateTimeString = formatter.format(dateTime);
System.out.println(formattedDateTimeString);
ONLINE DEMO
YYYY does not match with year part. In java 7 you need yyyy.
For T, use 'T' to match it
You're also missing the faction of millsecond part: .SSS
Try this:
String dateStr="2018-05-23T23:18:31.000Z";
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(utc);
Date convertedDate = sdf.parse(dateStr);
convertedDate.toString();
In Kotlin and using ThreeTenABP,
fun getIsoString(year: Int, month: Int, day: Int): String {
val localTime = ZonedDateTime.of(year, month, day, 0, 0, 0, 0, ZoneId.of("Z"))
val utcTime = localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC)
val isoString = utcTime.toInstant().toString() // 1940-15-12T00:00:00Z
val formattedIsoString = val formattedIsoString =
Instant.parse(isoString)
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter
.ofPattern("uuuu-MM-dd'T'HH:mm:ss")) // 'T' in quotes so that it is retained.
return formattedIsoString
}
// print it
print(getIsoString(1940, 15, 12)) // 1940-15-12T00:00:00
You can try this below the idea.
I am not an expert in JAVA but I did it in javascript/node.js
import * as momentTimeZone from 'moment-timezone';
let d = new Data(); // d = '2018-05-23T23:18:31.000Z'; or we can take this date
let finalOutput = momentTimeZone(d).tz(this.locationService.locationTimeZone).utc().format('YYYY-MM-DD HH:mm:ss');
console.log('Result: ', finalOutput); // Result: "2018-05-23 23:18:31";
It also works with moment.js.
Here is more about format.

Set hours minutes and seconds to 00 in ZonedDateTime or Instant

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

How to get Date from TimeStamp in java

I am trying to read a timestamp I have in my database mysql and save it to a Date variable in java.
I want it with this format: YYYY-MM-DD HH:MM:SS (24 hour format)
In my database I have a timestamp with that format but each time I try to get as timestamp I read 2014 and if I read it as Date with getDate()... I get "ago 16, 2014"
I'm not sure what you really want. Do you want to get a java.sql.Timestamp instance or do you want to get the timestamp as string with the mentioned pattern?
Maybe that helps:
ResultSet rs = ...
Timestamp t = rs.getTimestamp(...);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(t);
// get the timestamp from the DB
java.sql.Timestamp yourTimestamp = youNameItGetTimestamp();
// Create the corresponding Date object
java.util.Date date = new java.util.Date(yourTimestamp.getTime());
// show in a string
java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
java.lang.String printableDate = formatter.format(date);
System.out.println("here you have it: <" + printableDate + ">");
The other Answers are correct but use troublesome old legacy date-time classes. Instead use java.time classes.
Conversion
New methods have been added to the old classes to facilitate conversion such as java.sql.Timestamp::toInstant().
java.sql.Timestamp ts = myResultSet.getTimestamp( … ) ;
Instant instant = ts.toInstant();
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. Its toString method generates a String in one of the standard ISO 8601 formats.
String output = instant.toString();
2011-12-03T10:15:30Z
You could replace the T with a SPACE and delete the Z to get your format.
output = output.replace( "T" , " ").replace( "Z" , "" ) ;
2011-12-03 10:15:30
ZonedDateTime
If you want to see the same moment but through the lens of a particular time zone, generate a ZonedDateTime.
ZoneId zoneId = ZonedId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
Define a custom DateTimeFormatter object. Or use DateTimeFormatter.ISO_LOCAL_DATE_TIME and replace the T with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );
2011-12-03 05:15:30
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old 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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.
have you tried some thing like this :
java.sql.Date timeStamp = new java.sql.Timestamp( object.getDate() );
also this link may help you :
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
What's the type of your field? Is it a string/varchar? How about using SimpleDateFormat?
i.e.
final Date myDate = new SimpleDateFormat(FORMAT_STRING).parse(value);
See SimpleDateFormat documentation for more details.
BTW: A litte code and database definition would have been nice...

How to convert current date into string in java?

How do I convert the current date into string in Java?
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
Use a DateFormat implementation; e.g. SimpleDateFormat.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
tl;dr
LocalDate.now()
.toString()
2017-01-23
Better to specify the desired/expected time zone explicitly.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
java.time
The modern way as of Java 8 and later is with the java.time framework.
Specify the time zone, as the date varies around the world at any given moment.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ; // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;
2017-01-23
By default you get a String in standard ISO 8601 format.
For other formats use the java.time.format.DateTimeFormatter class.
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.
Faster :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
Most of the answers are/were valid.
The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised.
For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
We get a Calendar object and we look for the time in it.
( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic
altogether)
Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
public static Date getDateByString(String dateTime) {
if(dateTime==null || dateTime.isEmpty()) {
return null;
}
else{
String modified = dateTime + ".000+0000";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj = new Date();
Date dateObj1 = new Date();
try {
if (dateTime != null) {
dateObj = formatter.parse(modified);
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
}

Categories

Resources