I am trying to parse an SQL date string (ISO 9075) and that uses microseconds(!) instead of milliseconds, for example
2010-11-22 08:08:08.123456
However, SimpleDateFormat refuses to recognize a pattern like "yyyy-MM-dd HH:mm:ss.SSSSSS" and "yyyy-MM-dd HH:mm:ss.SSS" does not work, either.
The code I am using looks something like this:
String dateString = "2010-11-22 08:08:08.123456";
String pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";
try
{
format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(dateString, position);
System.out.println("Date 1: " + date1);
Date date2 = format.parse(dateString);
System.out.println("Date 2: " + date1);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
Whichever of the 2 patterns (".SSS" or ".SSSSSS") I use, date1 is printer as null, whereas date2 causes a parsing exception (java.text.ParseException: Unparseable date).
Maybe chop the remaining fraction part out of the dateString before parse the date? I have the following
String dateString = "2010-11-22 08:08:08.123456";
String fraction = dateString.substring(dateString.length() - 3);
String formatString = dateString.substring(0, dateString.length() - 3);
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
ParsePosition position = new ParsePosition(0);
try
{
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(formatString, position);
System.out.println("Date 1: " + date1);
System.out.println("Date 1 fraction: " + fraction);
Date date2 = format.parse(formatString);
System.out.println("Date 2: " + date2);
System.out.println("Date 2 fraction: " + fraction);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
This allow the date to parse until millisecond precision while you still retain the fraction micro part.
Hmm. Given that Date doesn't have microsecond resolution, if you know that all the SQL date strings have the full six digits after the seconds decimal point (2010-11-22 08:08:08.000000 for example), why not just chop off the final three digits and use SimpleDateFormat on the remainder?
You may want to look at DATE4J which specifically tries to deal with database dates, to nanosecond precision.
You might want to call the DateFormat parse, because I think it will cut off the string. Try:
Date date1 = format.parse(dateString);
Plus, don't use "SSSSS". According to specs, only "SSS" is valid for dateformat.
Other than that, I agree with cutting it off or parsing in SQL.
Plus, you have setLenient to false, so it's strict. So the string, being longer is going to cause it to fail. Maybe that's why it returns null. Unsure, would have to test.
tl;dr
Insert/Update.
myPreparedStatement.setObject(
… ,
Instant.parse( "2010-11-22 08:08:08.123456".replace( " " , "T" ) + "Z" )
) ;
Retrieval.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
String output = ldt.toString().replace( "T" , " " ) ; // Remove the standard ISO 8601 format’s use of `T` in the middle with the SQL-style SPACE.
java.time
Java 8 brings the new java.time package, to supplant the notoriously troublesome old java.util.Date, .Calendar, and SimpleDateFormat classes. Those old legacy classes are limited to milliseconds resolution while your input string has microseconds. You cannot cram six decimal places into a data type limited to three.
The date-time values in java.time have nanosecond resolution, more than enough for your microseconds. That means up to nine decimal places for a fractional second.
With JDBC 4.2 and later, use the Instant class directly.
Parse your input String. To comply with ISO 8601 format used by default in the java.time classes, replace the SPACE in the middle with a T. Your given example must be coming from a column type TIMESTAMP WITHOUT TIME ZONE which means not a specific moment, not a point on the timeline.
String input = "2010-11-22 08:08:08.123456".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
And if this input was meant to be a moment in UTC, append a Z. Then you do have a moment, a specific point on the timeline. For use with a column type of TIMESTAMP WITH TIME ZONE.
String input = "2010-11-22 08:08:08.123456".replace( " " , "T" ) + "Z" ;
Instant instant = Instant.parse( input ) ;
Send to your database.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myResultSet.getObject( … , Instant.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, 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.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Leaving this section intact as history.
Joda-Time
As noted above, you should avoid using the java.util.Date, .Calendar, and SimpleDateFormat classes. As of Java 8 you have the choice of using java.time or Joda-Time or both, as they each their strengths and weaknesses. Joda-Time also works in earlier versions of Java.
You can parse that string using Joda-Time.
Alternatively, if you have access to the java.sql.Timestamp that generated your string, you can simply pass the Timestamp object to the constructor of a DateTime. I suggest also passing a time zone as DateTime objects know their own assigned time zone.
DateTime dateTime = new DateTime( mySqlTimestamp, DateTimeZone.UTC );
or
DateTime dateTime = new DateTime( mySqlTimestamp, DateTimeZone.forID( "Europe/Paris" ) );
Joda-Time has a resolution of milliseconds. So either way you generate the DateTime (parsing or passing), you will loose the finer fraction of the second (ignored/truncated, not rounded).
If you have control over the SQL date which is an input to the java code, you could try and retrieve the date from SQL in a format which will work ("yyyy-MM-dd HH:mm:ss.SSS").
Related
I want to build a string with the locale date and hour, concatenated, that must be human readable and compatible with the most common OS file allowed characters as well. Something like:
6-23-20_03-06-50
I am using this as an automated filename suggestion for the user.
To achieve this, I have written the following code:
public class CustomDateProvider {
private static final String TWO_DIGIT_PATTERN = "%02d";
public static String getDashedDateAndHourFromDate(Date date) {
ZonedDateTime dateTime = date.toInstant().atZone(ZoneId.systemDefault());
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String localeDate = dateFormat.format(date);
String dashedDate = localeDate.replace("/", "-");
return dashedDate
+ "_"
+ String.format(TWO_DIGIT_PATTERN, hour)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, minute)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, second);
}
}
Thus, I am assuming the date separator char will always be "/", and I am not sure if this is always correct.
Either way, there are probably better ways to achieve my goal, and I would appreciate any improvement.
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
Avoid localized formats
You asked for text representing the date-time value in various localized formats. That approach is unwise in a file name.
Localized formats may well contain characters that would be problematic on various file systems. Your example MM/dd/yyyy format using slash characters might cause problems on some Unix/POSIX-oriented file systems.
Localized formats may be misinterpreted by humans who assume a different custom.
Localized formats may make difficult or impossible parsing that string back to a date-time value.
Instead, I strongly recommend using only standard ISO 8601 formats.
“Basic” variant of ISO 8601
You asked for:
must be human readable and compatible
I suggest sticking with the "basic" variant of ISO 8601 format that makes minimal use of delimiters. For compatibility with various filesystems you want to avoid slash, backslash, colon, and space characters.
The ISO 8601 format is in order of significance: year, month, day, hour, minute, second, fractional second. An uppercase T separates the date portion from the time-of-day portion. Such strings sort alphabetically as chronological.
UTC
I also suggest you stick with UTC (an offset of zero hours-minutes-seconds). For this, use Instant (or OffsetDateTime set to UTC).
Instant instant = Instant.now() ; // Capture current moment as seen in UTC.
Truncate if you do not want fractional seconds or minutes.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
You would do string manipulation to remove the hyphens between the year-month-day and the colons between the hour-minute-second.
String output = instant.replace( "-" , "" ).replace( ":" , "" ) ;
For 2021-01-23T12:30:35Z that would be:
20210123T123035Z
The trailing Z means UTC, and is pronounced “Zulu”.
Zoned moment
If you insist on using the date-time as seen in a particular time zone, use ZonedDateTime.
ZoneId z = ZoneId.systemDefault() ; // Or ZoneId.of( "Africa/Tunis" ) and such.
ZonedDateTime zdt = ZonedDateTime.now().truncatedTo( ChronoUnit.MINUTES ) ;
Specify a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String output = zdt.format( f ) ;
Example:
20210123T123035
I do not recommend omitting the zone or offset, but there you go if you insist.
If you insist your example format of 6-23-20_03-06-50, define a DateTimeFormatter to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M-d-uu'_'HH-mm-ss" ) ;
Allowing single-digit month or day is yet another thing I recommend against. As is the use of a two-digit year.
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 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….
Here is how you can get the locale Date_Time-
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTimeExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date and Time: "+currentDateTime);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("uuuu-MM-dd_hh-mm-ss");
System.out.println("Date Time in 12 Hour format - " + currentDateTime.format(pattern));
}
}
For more details please see this Get Locale Date_Time
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.
I have date and time on string type 20/03/2018, 18:20:44 Is it possible to change it to date format in java? I tried this code:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
Date date = formatter.parse(dateString);
return date;
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
I get unable to parse exception and returned with null
You've used the wrong string replacements inside your simple date format, it should be dd/MM/yyyy, HH:mm:ss. Note the capitalisation of the HH as well, your time is in 24 hour format so it must be HH over hh
So with the applied changes your code will look like this:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
return formatter.parse(dateString);
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
Read more on the various patterns available here, as an aside it is generally recommended to use the ISO 8601 format for dates, so yours would be yyyy-MM-ddTHH:mm:ss
You should use the same format with input string:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
You did two mistakes :
mm represents minutes. MM represents months.
But You specify mm in the month part of the date format.
the coma character : , provided in the input has also to be present in the date format.
So with a String input in this form : "20/03/2018, 18:20:44", you should use this DateFormat :
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");
tl;dr
Your formatting pattern was incorrect, using the wrong case and omitting the comma.
Also, you are using troublesome classes supplanted years ago by java.time classes.
LocalDateTime.parse( // Create a `LocalDateTime` object as the input string lacks any time zone or offset-from-UTC.
"20/03/2018, 18:20:44" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) // Define a formatting pattern to match the input.
)
.atZone( // Assign a time zone to the `LocalDateTime` to create a `ZonedDateTime` object.
ZoneId.of( "America/Los_Angeles" ) // Specify time zone to be assigned. Always use proper zone names `continent/region`; never use 3-4 character pseudo-zones.
)
2018-03-20T18:20:44-07:00[America/Los_Angeles]
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your string as a LocalDateTime since it lacks an indicator of time zone or offset-from-UTC.
String input = "20/03/2018, 18:20:44" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2018-03-20T18:20:44
Lacking a time zone or offset-from-UTC means that this does not represent a moment, is not a point on the timeline. Without the context of a zone/offset, this represents only a vague idea about potential moments along a range of 26-27 hours.
Apparently you are certain this input was actually meant to be in certain time zone. Apply a ZoneId to this LocalDateTime to get 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( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Conversion
Best to avoid the troublesome legacy classes. But if you must produce a java.util.Date to inter-operate with old code not yet updated for java.time, you can convert. To convert back and forth, call new methods on the old classes.
A java.util.Date represents a point on the timeline in UTC, with a resolution of milliseconds. So its replacement in java.time is Instant. An Instant is also a point on the timeline in UTC, with a finer resolution of nanoseconds. To get to a Date, we need an Instant, which we can pull from our ZonedDateTime.
Instant instant = zdt.toInstant() ; // Same moment, same point on the timeline, different wall-clock time.
Now we can get the legacy class object, Date, by calling Date.from.
java.util.Date date = Date.from( instant ) ; // Do this only if you *must* work with `Date` 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, 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.
I have a string containing a date in the form
04-Jan-15
and need to get the week number of the year out of it.
for the above example week 1(or 2 depending on locale and weekdays in December. never mind that).
I have this:
String[] startDate=dates[0].split("-");
int month,day,year;
year=2000+Integer.parseInt(startDate[2]);
day=Integer.parseInt(startDate[0]);
switch (startDate[1]){
case "Jan":
{
month=1;
break;
}
........
........
case "Dec":
{
month=12;
break;
}
}
Calendar temp=new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date tempDate = sdf.parse(day+"/"+month+"/"+year);
System.out.println("DATE:"+tempDate);
temp.setTime(tempDate);
System.out.println("Calendar Month:"+temp.MONTH);
System.out.println("Calendar Week:"+temp.WEEK_OF_YEAR);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This returns
DATE:Sun Jan 04 00:00:00 EET 2015
Calendar Month:2
Calendar Week:3
I tried (earlier) this
temp.set(year, month, day);
and was still getting wrong results.
Any idea?
tl;dr
For culturally-defined weeks…
LocalDate.parse(
"04-Jan-15" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get(
WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( )
) // Gets week number for a culturally-defined week-of-year.
For standard weeks…
LocalDate.parse(
"04-Jan-15" ,
DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US )
).get(
IsoFields.WEEK_OF_WEEK_BASED_YEAR
) // Gets standard ISO 8601 week number.
java.time
You are using troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. Much simpler now to solve your problem.
Parse your input string. Specify a 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, separators, and such.
String input = "04-Jan-15";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" , Locale.US );
LocalDate ld = LocalDate.parse( input , f );
Dump to console.
System.out.println( "input: " + input + " = " + ld );
input: 04-Jan-15 = 2015-01-04
Week number
Week number is culturally defined. To access week-of-year, you must specify a Locale whose culture you want to use in defining a week.
Locale locale = Locale.FRANCE;
WeekFields fields = WeekFields.of( locale );
TemporalField field = fields.weekOfWeekBasedYear( );
int weekNumber = ld.get( WeekFields.of( Locale.FRANCE ).weekOfWeekBasedYear( ) ); // Gets week number for a culturally-defined week-of-year.
ISO 8601 defines standard week numbers where week # 1 contains the first Thursday of the year, and begins on a Monday. The java.time class offer this approach built-in in the IsoFields class.
int weekNumber = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) // Gets standard ISO 8601 week number.
ISO 8601
By the way, that input string format is not good. When exchanging date-time values as text, always use ISO 8601 standard formats. These are used by default in java.time when parsing/generating 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.
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.
MONTH and WEEK_OF_YEAR in class Calendar are constants, not the month and week of year of any particular Calendar object.
You use these constants with the get(...) method. The constant indicates which field you want to get. Like this:
System.out.println("Calendar Month:" + temp.get(Calendar.MONTH));
System.out.println("Calendar Week:" + temp.get(Calendar.WEEK_OF_YEAR));
Also, there's a much easier way to parse a string like 04-Jan-15 into a Date object than doing it manually:
String text = "04-Jan-15";
DateFormat df = new SimpleDateFormat("dd-MMM-yy", Locale.US);
Date date = df.parse(text);
(Why are you first parsing the string manually, then converting it into another format dd/MM/yyyy and then parsing that again? That's much more complicated than necessary).
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...