split String without delimiters - java

My controller recieves this String "20120115Z" as a #RequestParam, representing a date.
I would like to transform it to this format: yyyy-MM-dd, so I would have a new string like this 2012-01-15.
As you can see, there's no delimiters, only the 'Z' always as the last character.
My approach was pretty obvious:
String data =
strData.substring(0, 4) + "-" +
strData.substring(4, 6) + "-" +
strData.substring(6, 8);
And it works, but as you know these "magic numbers" are something to avoid. I also tried to use a a regular expression like "^[^\s]{4}[^\s]{2}[^\s]{2}Z$", but without success.
Any idea?
UPDATE: Finally I've done it with Joda-Time DateTime class as #Brian Agnew suggested
DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYYMMdd'T'hhmm'Z'");
String strData = "20120115T0600Z";
DateTime dt = fmt.parseDateTime(strData);
printing method:
private static void printDateTime(DateTime dt) {
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
int hour = dt.getHourOfDay();
int minute = dt.getMinuteOfHour();
int second = dt.getSecondOfMinute();
int millis = dt.getMillisOfSecond();
String zone = dt.getZone().toString();
log.info("fecha: "
+ day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + millis
+ " " + zone + "\n");
}
Output
15/1/2012 6:0:0:0 UTC
Thanks everyone

I would perhaps use a Joda-Time DateTimeFormat.
Why ? It'll check the format, including valid values for hours/minutes/seconds, and give you back a suitable DateTime object which you can do what with (including reformat it using a similar approach).
You simply give it the format that you want to parse and it'll do all the rest. You have a date, so treat it as such.

Related

Remove special symbols/seperator e.g. point, comma, - , out of int

I want the person to let write in the date of his/her birthday, after that I want to compare it with the number of pi.
But I want the program to be flexible. So the date should not just be like
daymonthyear (13091975) but also like day.month.year (13.09.1975) or like day-month-year (13-09-1975)
I already found a idea but it does not work
String sep = "";
String geb = nf_datum.getText();
geb = geb.replaceAll(".", Matcher.quoteReplacement(sep));
i have found this idea with "replaceAll" here: replaceAll "/" with File.separator
I hope somebody can help me??
Using java8 you can get that string and define a DateTimeFormatter, this will give you the flexibility to parse a string into a LocalDate and you dont need to take care how the string "looks like", after that you will get a LocalDate object from which you can get the year, month and day
String geburtstag = "-";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("[ddMMyyyy]" + "[ddMMyyyy]" + "[dd.MM.yyyy]" + "[dd-MM-yyyy]");
// case1
geburtstag = "23.06.2017";
LocalDate ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());
// case2
geburtstag = "23062017";
ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());
// case3
geburtstag = "23-06-2017";
ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());

trying to fix a dereferencing error in java

I have a problem where i'm trying to find the date and time for a specific long value from the "new beginning of the universe", aka jan 1 1970.
I get a "cannot be dereferenced" error when i try to pass my new value to the toString thing.
What i don't get, is that this works for getting a time in millis and displaying it a more readable date/time format, so why not after i do a bunch of math with it?
import java.util.*;
public class Date {
public static void main(String[] args) {
Date mydate1 = new Date(10000);
System.out.println("The date and time of " +
mydate1.elapse + " from the Unix epoch is " + mydate1.getMyTime());
Date mydate2 = new Date(100000);
System.out.println("The date and time of " +
mydate2.elapse + " from the Unix epoch is " + mydate2.getMyTime());
Date mydate3 = new Date(1000000);
System.out.println("The date and time of " +
mydate3.elapse + " from the Unix epoch is " + mydate3.getMyTime());
Date mydate4 = new Date(10000000);
System.out.println("The date and time of " +
mydate4.elapse + " from the Unix epoch is " + mydate4.getMyTime());
Date mydate5 = new Date(100000000);
System.out.println("The date and time of " +
mydate5.elapse + " from the Unix epoch is " + mydate5.getMyTime());
Date mydate6 = new Date(1000000000);
System.out.println("The date and time of " +
mydate6.elapse + " from the Unix epoch is " + mydate6.getMyTime());
/*Date date7 = new Date(10000000000);
System.out.println("The date and time of " +
date7.elapse + " from the Unix epoch is " + date7.getTime());
Date date8 = new Date(100000000000);
System.out.println("The date and time of " +
date8.elapse + " from the Unix epoch is " + date8.getTime());*/
}
long elapse;
Date() {
elapse = 1;
}
Date(long elapseTime) {
elapse = elapseTime;
}
long getMyTime() {
//java.util.Date date = new.java.util.Date();
long currentMillis = System.currentTimeMillis();
long date = currentMillis + elapse - currentMillis;
System.out.println(date.toString());
You can't call toString() on a long (primitive type) -
// System.out.println(date.toString());
System.out.println(date); // <-- this would work.
System.out.println(String.valueOf(date)); // <-- this would be assignable to a
// String, but it prints the
// same value as the first example.
In
long date = currentMillis + elapse - currentMillis;
The variable date is a primitive (long) and not a object. toString is a method all java classes inherit from java.lang.Object and so will be available in all objects (that are instance of classes). long is just a primitive, primitives do not have methods, they do not inherit from Object either.
So all you need is
System.out.println(date);
The issue is in : System.out.println(date.toString())
date is of primitive type long (its not an object of wrapper class Long). Hence the method toString() is not available for 'date'. rather you can simple use :
System.out.println(date);
If you want to print the formatted Date use the following :
Dste d = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
System.out.println(sdf.format(d));

Stop date dropping zero's

How do I stop the ints dropping the zeros in the time? I've tried formatting it with
String.format("%02d", minutes);
but it doesn't work, I'm sure it's quite simple!
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
String curTime = hours + ":" + minutes;
String.format("%02d", minutes);
updatedat.setText("Updated at " + curTime);
Use a SimpleDateFormat object instead to format dates/times.
Date date = new Date(); // initializes to current time
DateFormat df = new SimpleDateFormat("h:mm");
updatedat.setText("Updated at " + df.format(date));
Read more about SimpleDateFormat and the formatting specifications here.
The reason it's not working is because String.format("%02d", minutes); is a function that returns a string
for your case if minutes was 8, String.format("%02d", minutes); would return 08
So, for this to work you'd have to have something like:
String curTime = hours + ":" + String.format("%02d", minutes);
I also agree that you shouldn't be formatting the time like this, use a date formatter.
One simple way of including 0's is to use a function like:
public String TwoCh(int i) { String s= "0" + Integer.toString(i); return s.substring(s.length() - 2); }
and then (notwithstanding the fact that getHours and getMinutes are both deprecated), you can do things like
String curTime = TwoCh(dt.getHours())+ ":" + TwoCh(dt.getMinutes());
I think what you want to do is to get the time in following format
22:01
In order to do that, use simpleDateFormat
you can read the full documentation, visit http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Joda DateTime to Timestamp conversion

I am trying to change the value of Timestamp by DateTimeZone in Joda :
DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
DateTimeZone.forID("anytimezone"));
Timestamp ts = new Timestamp(dt.getMillis());
For DateTime, value is : 2013-04-13T22:56:27.000+03:00
For TimeStamp, value is : 2013-04-13 22:56:27.0
Timestamp is coming without timezone difference.
How can I get the correct Timestamp with TimeZone ?
For example I want to get "2013-05-13 01:56:27.0".
Edit : using MySQL, column type is TIMESTAMP of course, rs is ResultSet.
It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".
An example: two people look at the clock at the same moment. The timestamp is the same, right?
But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).
Their perception is different but the moment is the same.
You can find more details in this answer.
UPDATE
OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".
Let's look at your original question code broken down like this:
// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");
// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));
// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());
I haven't run this code but I am certain it will print true and the same number of milliseconds each time:
System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));
System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());
But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].
In your own answer you are artificially adding an offset and creating a "wrong" time.
If you use that timestamp to create another DateTime and print it out it will be offset twice.
// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));
P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.
JUnit Test as proof
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
public class WorldTimeTest {
private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
private TimeZone londonTimeZone;
private TimeZone newYorkTimeZone;
private TimeZone sydneyTimeZone;
private long nowInMillis;
private Date now;
public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
SimpleDateFormat result = new SimpleDateFormat(pattern);
// Must explicitly set the time zone with "setCalendar()".
result.setCalendar(Calendar.getInstance(timeZone));
return result;
}
public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
return createDateFormat(pattern, TimeZone.getDefault());
}
public static SimpleDateFormat createDateFormat() throws Exception {
return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
}
public void printSystemInfo() throws Exception {
final String[] propertyNames = {
"java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
"os.name", "os.version", "os.arch",
"user.language", "user.country", "user.script", "user.variant",
"user.language.format", "user.country.format", "user.script.format",
"user.timezone" };
System.out.println();
System.out.println("System Information:");
for (String name : propertyNames) {
if (name == null || name.length() == 0) {
continue;
}
String value = System.getProperty(name);
if (value != null && value.length() > 0) {
System.out.println(" " + name + " = " + value);
}
}
final TimeZone defaultTZ = TimeZone.getDefault();
final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
final int userOffset = TimeZone.getTimeZone(System
.getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
final Locale defaultLocale = Locale.getDefault();
System.out.println(" default.timezone-offset (hours) = " + userOffset);
System.out.println(" default.timezone = " + defaultTZ.getDisplayName());
System.out.println(" default.timezone.id = " + defaultTZ.getID());
System.out.println(" default.timezone-offset (hours) = " + defaultOffset);
System.out.println(" default.locale = "
+ defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
+ " (" + defaultLocale.getDisplayLanguage()
+ "," + defaultLocale.getDisplayCountry() + ")");
System.out.println(" now = " + nowInMillis + " [ms] or "
+ createDateFormat().format(now));
System.out.println();
}
#Before
public void setUp() throws Exception {
// Remember this moment.
now = new Date();
nowInMillis = now.getTime(); // == System.currentTimeMillis();
// Print out some system information.
printSystemInfo();
// "Europe/London" time zone is DST aware, we'll use fixed offset.
londonTimeZone = TimeZone.getTimeZone("GMT");
// The same applies to "America/New York" time zone ...
newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
// ... and for the "Australia/Sydney" time zone.
sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
}
#Test
public void testDateFormatting() throws Exception {
int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
londonCalendar.setTime(now);
int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
newYorkCalendar.setTime(now);
int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
sydneyCalendar.setTime(now);
// Check each time zone offset.
assertThat(londonOffset, equalTo(0));
assertThat(newYorkOffset, equalTo(-5));
assertThat(sydneyOffset, equalTo(10));
// Check that calendars are not equals (due to time zone difference).
assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
assertThat(londonCalendar, not(equalTo(sydneyCalendar)));
// Check if they all point to the same moment in time, in milliseconds.
assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));
// Check if they all point to the same moment in time, as Date.
assertThat(londonCalendar.getTime(), equalTo(now));
assertThat(newYorkCalendar.getTime(), equalTo(now));
assertThat(sydneyCalendar.getTime(), equalTo(now));
// Check if hours are all different (skip local time because
// this test could be executed in those exact time zones).
assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
// Display London time in multiple forms.
SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + londonOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfLondonNoTZ.format(londonCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfLondonWithTZ.format(londonCalendar.getTime()));
System.out.println(" time (default format) = "
+ londonCalendar.getTime() + " / " + londonCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
+ " / " + createDateFormat().format(londonCalendar.getTime()));
// Display New York time in multiple forms.
SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + newYorkOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (default format) = "
+ newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
+ " / " + createDateFormat().format(newYorkCalendar.getTime()));
// Display Sydney time in multiple forms.
SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + sydneyOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfSydneyNoTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfSydneyWithTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (default format) = "
+ sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
+ " / " + createDateFormat().format(sydneyCalendar.getTime()));
}
#Test
public void testDateParsing() throws Exception {
// Create date parsers that look for time zone information in a date-time string.
final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
// Create date parsers that ignore time zone information in a date-time string.
final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
// We are looking for the moment this millenium started, the famous Y2K,
// when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
// Which of these is the right one?
// a) "2000-01-01T00:00:00.000-00:00"
// b) "2000-01-01T00:00:00.000-05:00"
// c) "2000-01-01T00:00:00.000+10:00"
// None of them? All of them?
// For those who guessed it - yes, it is a trick question because we didn't specify
// the "where" part, or what kind of time (local/global) we are looking for.
// The first (a) is the local Y2K moment in London, which is at the same time global.
// The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
// The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
// The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
// The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.
// These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);
// Check if they all point to the same moment in time.
// And that parser ignores its own configured time zone and uses the information from the date-time string.
assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
assertThat(milleniumInSydney, equalTo(milleniumInLondon));
// These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);
// Check if they all point to the same moment in time.
assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));
// Check if the time zone offset is correct.
assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// These are also local Y2K moments, just withouth the time zone information.
final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);
// Check if these are the same as the local moments with time zone information.
assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));
// Check if they all point to the same moment in time.
assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
assertThat(midnightInSydney, not(equalTo(midnightInLondon)));
// Check if the time zone offset is correct.
assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// Final check - if Y2K moment is in London ..
final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
// .. New York local time would be still 5 hours in 1999 ..
final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
// .. and Sydney local time would be 10 hours in 2000.
final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";
final String londonTime = londonFormatTZ.format(milleniumInLondon);
final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);
// WHat do you think, will the test pass?
assertThat(londonTime, equalTo(Y2K_LONDON));
assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
}
}
Actually this is not a duplicate question. And this how i solve my problem after several times :
int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());
This is the way to get offset from desired timezone.
Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.
DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
DateTimeZone.forID("anytimezone"));
Now we will add our offset to the datetime, and get the timestamp from it.
dt = dt.plusMillis(offset);
Timestamp ts = new Timestamp(dt.getMillis());
May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.
//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));
I've solved this problem in this way.
String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);
In this way you ignore the server TimeZone forcing your chosen TimeZone.

how to convert string to date and keep the format correct

I am reading in a String from a text file which contains a date in the form of yyMMdd I then want to convert it to type date but when I do that it loses its format. here is an exmaple of what I have tried
String strDate = matcher.group(10); // strDate would contain 111107
SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
Date date = formatter1.parse(strDate); // after parsing it, the format changes to Thu Nov 03 00:00:00 EDT 2011
But if I take date and put it back into a string like so String tDate = formatter1.format(date); the string then contains the date in the format Id like to see 111107.
Is there a way I can do this? maybe if I could some how call the format function to return a date object instead of String, thanks.
Edit
I read a list of dates in from a file and load them into a map I then compare those dates to the current date which is also in the yyMMdd format and then if the date from the map is more then a week earlier than the current date I prompt the user for input and then write the date and other related info to a file, in the yyMMdd format. The reason I use a map is each line of the text file contains some information and a unique name, and I compared the date for that specific line of data so I do a map.get(aName)
here is the code, hope it helps
dbConnect();
stmt = conn.createStatement();
String query = "select * from OBJECT_BAC_EV where instance = 12";//VALUE <> 'Normal'";
rslt = stmt.executeQuery(query);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String dateNow = formatter.format(currentDate.getTime());
Date curDate = (Date)formatter.parse(dateNow);
currentDate.setTime(curDate);
currentDate.add(Calendar.DAY_OF_MONTH, -7);
dateNow = formatter.format(currentDate.getTime());
curDate = (Date)formatter.parse(dateNow);
Calendar cDate = Calendar.getInstance();
SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
String strDate = f.format(cDate.getTime());
while(rslt.next())
{
System.out.println(rslt.getRow());
String aValue = rslt.getString("VALUE");
String aName = rslt.getString("NAME");
String aObjRef = rslt.getString("ObjRef");
if(aNoteMap.containsKey(aName))
{
String n = aNoteMap.get(aName);
if(aDateMap.get(aName).before(curDate))
{
int answer = JOptionPane.showConfirmDialog(null, "Would you like to use last weeks note? " + n, "Hey", JOptionPane.YES_NO_OPTION);
if( answer == JOptionPane.YES_OPTION)
{
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else if( answer == JOptionPane.NO_OPTION)
{
String newNote = JOptionPane.showInputDialog("Enter new note");
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ newNote + (System.getProperty("line.separator")));
}
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + strDate + " "
+ "" + (System.getProperty("line.separator")));
}
System.out.println("its closing output..");
output.close();
}
The Date class has no "internal" format, it only represents date elements. To output it using a specific format, you need to do the way you did: String tDate = formatter1.format(date);
The reason why you think it has the "wrong format" is probably because when you try to output it, it does a toString() by default, which doesn't format it the way you want.
If you give us more details about how you want to use that date (include your code), then we might be able to provide suggestions on how to inject the formatter into it.
Date always stores the complete information including time. If you parse the date with a SimpleDateFormat that does not contain time info, these fields are set to 0 as in your example.
Date does not store any format info itself.
The SimpleDateFormat.format method always returns a String. It represents the 'date' parameter as a String, with the specified format. For example:
SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');
Date date = sdf.parse("110510");
String sDate = sdf.format(date); //"110510"
SimpleDateFormat sdf2 = new SimpleDateFormat('yyyy.MM.dd');
String sDate2 = sdf2.format(date); //2011.05.10
It's the best thing for formatting a Date Object.
Written using joda-time, it would like this :
String str = "110107";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendYearOfCentury(2, 2)
.appendMonthOfYear(2)
.appendDayOfWeek(2)
.toFormatter();
DateTime dateFromDB = formatter.parseDateTime(str);//create DateTime instance
System.out.println("Date:" + formatter.print(dateFromDB));//toString in required format
And it has many other benefits, apparently it will replace the existing Java date libs, which have always been rather painful, in upcoming java releases.
One of the benefits is
DateTime now = new DateTime();
Integer compared = now.minusWeeks(1).compareTo(dateFromDB);
And compareTo does the expected
You could try something like:
class MyDate extends java.util.Date {
static final SimpleDateFormat yymmddFormat = new SimpleDateFormat("yyMMdd");
public MyDate (String s) throws ParseException {
super(yymmddFormat.parse(s).getTime());
}
public String toString () {
return yymmddFormat.format(this);
}
}
Use this class everywhere you currently use a Date object. This should make all your dates look as you want them.

Categories

Resources