Article View: borland.public.jbuilder.java.language
Article #19150Re: Date type to/from string
From: James D. Frentress
Date: Wed, 11 Mar 1998 00:00
Date: Wed, 11 Mar 1998 00:00
48 lines
2404 bytes
2404 bytes
Tad Frysinger wrote:
> Well, maybe I missed something, but I was all over Calendar and
> GregorianCalendar, and didn't see a way to construct a *Date* from a
> string (the default toString() method of Date uses a formatter very
> similar to what you posted).
Does this help?
// constants
int YEAR = 0, MONTH = 1, DATE = 2;
// current date and time
Calendar cal = Calendar.getInstance();
// see
System.out.println("YEAR: " + cal.get(Calendar.YEAR));
System.out.println("MONTH: " + cal.get(Calendar.MONTH));
System.out.println("DAY: " + cal.get(Calendar.DATE));
// or, if you prefer, set it to some date
cal.setTime(new Date());
// convert date to a string (you decide how much precision you want,
I'll just show day precision)
String[] ydm = new String[3];
ydm[YEAR] = Integer.toString(cal.get(Calendar.YEAR));
ydm[MONTH] = Integer.toString(cal.get(Calendar.MONTH));
ydm[DATE] = Integer.toString(cal.get(Calendar.DATE));
// send the string to an exotic place for fun and games
// exotic place unpacks string and recreates the calendar from the
string
// adding a day to show it really changed
Calendar calNew = Calendar.getInstance();
try {
calNew.set(Integer.parseInt(ydm[YEAR].trim()),
Integer.parseInt(ydm[MONTH].trim()), Integer.parseInt(ydm[DATE].trim())
+ 1);
} catch (NumberFormatException ex){}
// see
System.out.println("\nYEAR: " + calNew.get(Calendar.YEAR));
System.out.println("MONTH: " + calNew.get(Calendar.MONTH));
System.out.println("DAY: " + calNew.get(Calendar.DATE));
Jim // not an executable line of code :)
Technical Details
Message-ID:
<3506D174.D1779EDB@ForAWhile.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<MPG.f6f3422293a76d09897c7@forums.borland.com> <35059639.B429F072@csi.com> <MPG.f6f7f045dce2f2d9897cb@forums.borland.com> <3505D755.B6F361B@ForAWhile.com> <MPG.f706587e964244a9897cf@forums.borland.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,97ec465ac7d926cb X-Google-Attributes: gidf74b3,public From: "James D. Frentress" <Broken@ForAWhile.com> Subject: Re: Date type to/from string Date: 1998/03/11 Message-ID: <3506D174.D1779EDB@ForAWhile.com> X-Deja-AN: 333046258 Content-Transfer-Encoding: 7bit References: <MPG.f6f3422293a76d09897c7@forums.borland.com> <35059639.B429F072@csi.com> <MPG.f6f7f045dce2f2d9897cb@forums.borland.com> <3505D755.B6F361B@ForAWhile.com> <MPG.f706587e964244a9897cf@forums.borland.com> X-Priority: 3 (Normal) Content-Type: text/plain; charset=us-ascii Organization: Microsoft Mime-Version: 1.0 Newsgroups: borland.public.jbuilder.java.language