Date conversion in value read from excel in java - java

Mates,
I have a Date object which get populated with a value after reading from a excel
Date mydate = cell.getDateCellValue();
value loaded is *"Sat Jan 09 00:00:00 IST 2016"
I dont know why this format value is given out from excel though its displayed on different format in excel.
I want to convert this DATE into dd-mm-yyyy format. How can this be done?
Tried this
String ms= "Sat Jan 09 00:00:00 IST 2016" ;
SimpleDateFormat formater = new SimpleDateFormat("mm-dd-yy");
Date result = formater.parse(ms);
System.out.println(result);
but gives output same as input.

You need to create your own Date class and override toString method with which ever format you want it to return #ApachePOI
public class CustomDate extends Date
{
public CustomDate(String string)
{
super(string);
}
#Override
public String toString()
{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String format = formatter.format(this);
return format;
}
}
And the main method
public static void main(String[] args)
{
Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
String dateString = date.toString();
CustomDate customDate = new CustomDate(dateString);
System.out.println(dateString);
System.out.println(customDate.toString());
}
Use whatever format you want inside your toString method

Do not conflate a date-time object with text that represents its value. A java.util.Date has no “format”. You are seeing text generated by that object’s toString method. That text does not exist inside the object. That class’ toString lies, applying the JVM’s current default time zone to the UTC value actually stored inside. One of many reasons to avoid this class altogether.
That Date class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Convert your java.util.Date object to an Instant.
In Java 8 and later, look for new conversion methods added to the old classes. For Java 6 & Java 7, you'll be using the ThreeTen-Backport project. There you'll find a DateTimeUtil class offering conversion methods.
From our Instant, we can get a date. But first we must apply a time zone to move that Instant from UTC to the zone by which you want to perceive the date. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate a string using a DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd -MM-uuuu" , Locale.US ) ;
String output = zdt.format( f ) ;

Related

Java convert ISO 8601 string to Date ignoring offset

I have a string coming to me in the following format "yyyy-MM-dd'T'HH:mm:ssZ" ex: 2020-09-09T09:58:00+0000" offset is UTC.
I need the string to be converted to a Date object without the offset "+0000" being applied, but I keep getting a different time when running my code:
DateTimeFormatter isoFormat = ISODateTimeFormat.dateTimeParser();
Date date = isoFormat.parseDateTime("2020-09-09T09:58:00+0000").toDate();
// Wed Sep 09 05:58:00 EDT 2020
As you can see above the date has changed.
Instead, I would like to keep the same date and time like: Wed Sep 09 09:58:00, so I can convert this Date object to a String with "yyyy-MM-dd", "HH:mm:ss", and "yyyy-MM-dd'T'HH:mm:ss" format respectively.
The first and most important part of the answer is: don’t convert to an old-fashioned Date. Either stick to Joda-Time or migrate to java.time, the modern Java date and time API, as already covered in the good answer by Arvind Kumar Avinash.
Since you are already using Joda-Time, I am showing you a Joda-Time solution. The trick for persuading the formatter into keeping the time and offset from the string parsed is withOffsetParsed().
DateTimeFormatter isoFormat
= ISODateTimeFormat.dateTimeParser().withOffsetParsed();
String incomingString = "2020-09-09T09:58:00+0000";
DateTime dateTime = isoFormat.parseDateTime(incomingString);
However! If I have guessed correctly that you want to store date and time in UTC (a recommended practice), better than withOffsetParsed() is to specify UTC on the parser:
DateTimeFormatter isoFormat
= ISODateTimeFormat.dateTimeParser().withZoneUTC();
Now you will also get the correct time if one day a string with a non-zero UTC offset comes in.
In any case we may now format your obtained DateTime into the strings you requested.
String dateString = dateTime.toString(ISODateTimeFormat.date());
System.out.println(dateString);
String timeString = dateTime.toString(ISODateTimeFormat.hourMinuteSecond());
System.out.println(timeString);
String dateTimeString = dateTime.toString(ISODateTimeFormat.dateHourMinuteSecond());
System.out.println(dateTimeString);
Output:
2020-09-09
09:58:00
2020-09-09T09:58:00
What was wrong with using Date? First, the Date class is poorly designed and long outdated. Second, a Date was just a point in time, it didn’t have a concept of date and time of day (they tried building that into it in Java 1.0, but gave up and deprecated it in Java 1.1 in 1997). So a Date cannot hold the date and time of day in UTC for you.
What happened in your code was that you got a Date representing the correct point in time. Only when you printed that Date you were implicitly invoking its toString method. Date.toString() confusingly grabs the JVM’s time zone setting (in your case apparently North American Eastern Time) and uses it for rendering the string to be returned. So in your case the point in time was rendered as Wed Sep 09 05:58:00 EDT 2020.
I recommend you do it with the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// The given date-time string
String strDateTime = "2020-09-09T09:58:00+0000";
// Define the formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ");
// Parse the given date-time string into OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, formatter);
// Output OffsetDateTime in the default format
System.out.println(odt);
// Print OffsetDateTime using the defined formatter
String formatted = formatter.format(odt);
System.out.println(formatted);
}
}
Output:
2020-09-09T09:58Z
2020-09-09T09:58:00+0000
Note: java.util.Date does not represent a Date/Time object. It simply represents the no. of milliseconds from the epoch of 1970-01-01T00:00:00Z. It does not have any time-zone or zone-offset information. When you print it, Java prints the string obtained by applying the time-zone of your JVM. I suggest you stop using java.util.Date and switch to the modern date-time API.
Using joda date-time API, you can do it as follows:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class Main {
public static void main(String[] args) {
// The given date-time string
String strDateTime = "2020-09-09T09:58:00+0000";
// Define the formatter
DateTimeFormatter isoFormat = ISODateTimeFormat.dateTimeParser();
DateTime dateTime = isoFormat.parseDateTime("2020-09-09T09:58:00+0000");
// Display DateTime in the default format
System.out.println(dateTime);
// Define formatter for ouput
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC();
// Display DateTime in the defined output format
String formatted = outputFormat.print(dateTime);
System.out.println(formatted);
}
}
Output:
2020-09-09T10:58:00.000+01:00
2020-09-09T09:58:00+0000

Is there a function in java which helps to format and return the formatted date as output?

I'm trying to format date in java using SimpleDateFormat class. I have written a function which takes in string as a parameter and returns date as a output having the desired format. The problem arises when i try to parse the date in order to convert the string to date , the value is returned as Wed Jul 03 00:00:00 IST 2019 , instead of yyyy-MM-dd format .
private static final String DOB_FORMAT = "yyyy-MM-dd";
public static Date convertStringToDateFormatYYYYMMDD(String date) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(DOB_FORMAT, Locale.ENGLISH);
Date parsedDate = null;
try {
parsedDate = sdf.parse(date);
LOG.info("Date formated " + parsedDate);
return parsedDate;
} catch (ParseException e) {
LOG.info("Date Parsing Issue - date :" + date);
}
}
return null;
}
The result value should be returned as yyyy-MM-dd, instead of Wed Jul 03 00:00:00 IST 2019
Avoid legacy date-time classes
I'm trying to format date in java using SimpleDateFormat class.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes, with the adoption of JSR 310.
ISO 8601
DOB_FORMAT = "yyyy-MM-dd"
That format happens to comply with the ISO 8601 standard.
The java.time classes comply with the standard as well, using those formats by default when parsing/generating strings.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
String input = "2019-01-23" ; // January 23, 2019
LocalDate localDate = LocalDate.parse( input ) ;
Text has formats, not date-time objects
You Question also says:
value is returned as Wed Jul 03 00:00:00 IST 2019 , instead of yyyy-MM-dd format .
Be clear that date-time objects do not have a “format”. Only text strings have a format. A date-time object is not a text string. A date-time object parses a text string to generate a date-time value, and a date-time object can generate text representing its date-time value. But the date-time object and the text are distinct and separate from one another.
Avoid java.util.Date
Date parsedDate = null;
The terrible java.util.Date class represents a date with time-of-day in UTC (an offset from UTC of zero hours-minutes-seconds). But you want only a date, without the time-of-day and without an offset or time zone. So square peg, round hole. Instead, use appropriate types. And stop using those legacy date-time classes; use only java.time classes.
Generating text
To generate a string in standard ISO 8601 format, simply call toString.
String output = localDate.toString() ;
2019-01-23
To generate a string automatically-localized:
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = localDate.format( f ) ;
See this code run live at IdeOne.com.
23 janv. 2019
Date object is not formatted itself. You can return a formatted String containing the information.

how to add seconds to string time stamp (yyyy-mm-ddTH:i:s+tz) in java

I have a String variable called time is 2016-11-30T00:06:42+05:30
and a duration 32700 i.e 545 minutes.
I want to add duration to above string time stamp and need to calculate start time and end time.
So i want to get StartTime:00:06 and EndTime:09:05.
I tried this but doesn't work
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = sdf.parse(startTime.toString());
Timestamp ts_now = new Timestamp(date.getTime());
System.out.println(">>>>>>"+date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ts_now.getTime());
cal.add(Calendar.SECOND, Integer.parseInt(Value.toString()));
Timestamp later = new Timestamp(cal.getTime().getTime());
System.out.println(">>>>>>"+later);
I tried with X ,Z but got error like
Exception in thread "main" java.text.ParseException: Unparseable date: "2016-11-30T00:06:42+05:30"
at java.text.DateFormat.parse(DateFormat.java:366)
at oneraise.radis.thread.mavenproject1.ParseJson.main(ParseJson.java:48)
I am new to java can anybody help me
Thanks
tl;dr
OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" )
.plus( Duration.ofSeconds( 32_700L ) )
Details
Avoid the troublesome and confusing date-time classes such as java.util.Date and Calendar, now legacy, supplanted by the java.time classes.
Your input string complies with standard ISO 8601 formats. Such strings can be directly parsed by java.time classes with no need to specify a formatting pattern.
Parse as an OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" );
The ZonedDateTime class used in another Answer is inappropriate here. This input string contains only an offset-from-UTC, not a full time zone such as Asia/Kolkata. So OffsetDateTime is the class to use here.
The Duration class handles your span of time, a count of seconds.
Duration d = Duration.ofSeconds( 32_700L );
Add to your date-time object.
OffsetDateTime odtLater = odt.plus( d );
Tip: To view the OffsetDateTime value in UTC, extract an Instant.
Instant instant = odt.toInstant();
Database
For database access, your JDBC 4.2 compliant driver may be able to work with java.time objects via the get/setObject methods.
If so, no need to use the old java.sql.Timestamp class or its siblings.
myPreparedStatement.setObject( … , odt );
If not, use the new conversion methods added to the old date-lime classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( odt.toInstant() );
Here is the format for the string you have given
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
Date date;
try
{
Here I've parsed the string you have given. If you want the current time, use date = new Date();
date = sdf.parse("2016-11-30T00:06:42+05:30");
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Here I've added your interval
cal.add(Calendar.SECOND, 32700);
System.out.println(cal.getTime());
String output = outputFormat.format(date);
System.out.println(output);
String output2 = outputFormat.format(cal.getTime());
System.out.println(output2);
}
catch (ParseException e)
{
e.printStackTrace();
}
Here is the output. I'm in a different timezone.
Tue Nov 29 13:06:42 CST 2016
Tue Nov 29 22:11:42 CST 2016
13:06
22:11
If in your code I change the initialization of the date format to:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
— and I set my computer’s time zone to IST, I get the following output:
>>>>>>Wed Nov 30 00:06:42 IST 2016
>>>>>>2016-11-30 09:11:42.0
Alternatively you may use the Java 8 time classes, but convert to good old Timestamp if this is what you need. Edit: I am thankful to Basil Bourque for correctly pointing out that OffsetDateTime is the class to use, and for the method for converting to timestamp. See his answer for the full explanation.
Instant laterInstant = OffsetDateTime.parse(startTime.toString())
.plusSeconds(Integer.parseInt(value.toString()))
.toInstant();
Timestamp ts = Timestamp.from(laterInstant);
System.out.println(ts);
This prints:
2016-11-30 09:11:42.0
I believe the above does what you want.

Not able to convert EST to IST time in Java

Hi i am currently work on creating Desktop application using Swing.I was able to convert IST to EST time using Date class in java but not able to convert EST to IST time and it gives same EST time as IST time. Please find the below code .
ChangetoEST function is giving correct EST time from IST time.
ChangetoIST function is not giving correct IST time from EST time and showing given EST time as IST time.
public String changetoEST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
formatter.setTimeZone(tzInAmerica);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
public String changetoIST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInIndian = TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tzInIndian);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
The parse calls are done without you explicitly setting a time zone, which means that parsing is done using your default time zone.
Set the source time zone before parsing, parse, set time zone to target time zone, and format result.
E.g.
public static String istToEst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("Asia/Calcutta"),
TimeZone.getTimeZone("America/New_York"));
}
public static String estToIst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("Asia/Calcutta"));
}
private static String changeTimeZone(String dateInput, TimeZone sourceTimeZone,
TimeZone targetTimeZone) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
formatter.setTimeZone(sourceTimeZone);
Date date = formatter.parse(dateInput);
formatter.setTimeZone(targetTimeZone);
return formatter.format(date);
}
Test
String dateInput = "08/22/2016 02:21 AM";
System.out.println(dateInput);
System.out.println(istToEst("08/22/2016 02:21 AM"));
System.out.println(estToIst("08/22/2016 02:21 AM"));
Output
08/22/2016 02:21 AM
08/21/2016 04:51 PM
08/22/2016 11:51 AM
Set formatter to the source timezone before parsing (this is the step you are missing), then set it to the destination timezone before formatting, otherwise it parses it using the local timezone, which is IST for you.
Also you should just be able to return sDateInAmerica directly, you don't need to re-parse then re-format it a second time.
java.time
You are using troublesome old legacy date-time classes, now supplanted by the java.time classes.
We parse the input string as a LocalDateTime as it lacks any info about offset-from-UTC or time zone (offset plus rules for anomalies such as DST).
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/yyyy hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
Apply a time zone to get an actual moment on the timeline, a ZonedDateTime object.
ZoneId zNewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdtNewYork = ldt.atZone( zNewYork );
To see the same moment through the lens of another time zone, another wall-clock time, adjust into another ZoneId. Notice that we are not going through another LocalDateTime as the purpose of that class is to forget any information about offset or time zone. We want the opposite, to use the info about time zone to adjust wisely between zones. So while New York is behind UTC by four hours, India is ahead of UTC by five and a half hours. So we need a total of nine and a half hour adjustment, which may include a change in date.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtNewYork.withZoneSameInstant( zKolkata ); // Same simultaneous moments on the timeline.
Generate String
You can generate a String in any format you desire to represent the date-time value.
String output = zdtKolkata.format( f );
Generally better to let java.time automatically localize for you.
Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( l );
String output = zdtKolkata.format( f );

Removing time from my Date variable

I have my Date of Birth variable which is initially of type int. It is then parsed toString() and parsed to Date with simpleDateFormat.
The only issue is that it keeps returning it's default time including the date.
public Date getDob(){
String format = Integer.toString(this.dob);
try{
date = new SimpleDateFormat("ddMMyyyy").parse(format);
}catch(ParseException e){
return null;
}
return date;
}
Returns: Sat Jan 16 00:00:00 CET 1999 [ I want to remove the bold time ]
Thank you very much for your help!
Solution:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
return date;
}
You cannot change toString() method of Date class,
what you are doing is you are parsing some String to Date and returning Date instance and trying to print it which internally invokes toString() of Date and it has fixed format,
You can use format() method to convert Date to String and print it in whatever format you want
A java.util.Date object by definition has both a date portion and a time-of-day portion.
Date-Time != String
Understand that a date-time object is not a String. We create String representations of the date-time value contained within a date-time object, but doing so is generating a fresh String object completely separate from the date-time object.
LocalDate
If you want only a date, without the notion of time-of-day, use the LocalDate class found in both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time).
Joda-Time
By default, Joda-Time uses the ISO 8601 standard formats. If you want Strings in other formats, explore the DateTimeFormat class (a factory of DateTimeFormatters).
Example code in Joda-Time 2.3.
String input = "01021903"; // First of February, 1903.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyy" );
LocalDate dateOfBirth = formatter.parseLocalDate( input );
String outputStandard = dateOfBirth.toString(); // By default, the ISO 8601 format is used.
String outputCustom = formatter.print( dateOfBirth );
Try this one
Date originalDate = new Date();
long timeInMills = originalDate.getTime();
Date newDate = new Date(timeInMills);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
System.out.println(date);
output:
Wed Apr 30
If you want to store the date in long (in milliseconds) if needed.
For more pattern have a look at SimpleDateFormat

Categories

Resources