Java Tutorial/Data Type/Date
Содержание
- 1 Convert a String Date Such as 10 into a java.util.Date Object
- 2 Convert Date into milliseconds example
- 3 Convert from a java.util.Date Object to a java.sql.Date Object
- 4 Convert the Current Time to a java.sql.Date Object
- 5 Create a java.sql.Time Object from java.util.Date
- 6 Create a java.util.Date Object from a Year, Month, Day Format
- 7 Create java Date from specific time example
- 8 Create Yesterday"s Date from a Date in the String Format of MM/DD/YYYY
- 9 Determine the Day of the Week from Today"s Date
- 10 ISO ate parsing utility.
- 11 Obtaining a Date Object From a String
- 12 Parses a string representing a date by trying a variety of different parsers.
- 13 Perform date validations
- 14 Show date and time using only Date methods.
- 15 The java.util.Date Class
Convert a String Date Such as 10 into a java.util.Date Object
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class MainClass {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String date = "2003/01/10";
java.util.Date utilDate = null;
try {
utilDate = formatter.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date:" + date);
System.out.println("utilDate:" + utilDate);
}
}
date:2003/01/10 utilDate:Fri Jan 10 00:00:00 PST 2003
Convert Date into milliseconds example
import java.util.Date;
public class Main {
public static void main(String args[]) {
Date date = new Date();
System.out.println("Date is : " + date);
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " + date.getTime());
}
}
Convert from a java.util.Date Object to a java.sql.Date Object
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
utilDate:Fri Feb 02 12:55:46 PST 2007 sqlDate:2007-02-02
Convert the Current Time to a java.sql.Date Object
import java.sql.Date;
import java.text.ParseException;
import java.util.Calendar;
public class MainClass {
public static void main(String[] args) throws ParseException {
Calendar currenttime = Calendar.getInstance();
Date sqldate = new Date((currenttime.getTime()).getTime());
}
}
Create a java.sql.Time Object from java.util.Date
java.sql.Time descends from java.util.Date but uses only the hour, minute, and second values.
import java.text.ParseException;
import java.util.Date;
public class MainClass {
public static void main(String[] args) throws ParseException {
new java.sql.Time(new Date().getTime());
}
}
Create a java.util.Date Object from a Year, Month, Day Format
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class MainClass {
public static void main(String[] args) throws ParseException {
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
utilDate:Fri Dec 12 00:00:00 PST 2003
Create java Date from specific time example
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date d = new Date(365L * 24L * 60L * 60L * 1000L);
System.out.println(d);
}
}
Create Yesterday"s Date from a Date in the String Format of MM/DD/YYYY
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MainClass {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
GregorianCalendar gc = new GregorianCalendar();
java.util.Date d = sdf.parse("12/12/2003");
gc.setTime(d);
System.out.println("Input Date = " + sdf.format(d));
int dayBefore = gc.get(Calendar.DAY_OF_YEAR);
gc.roll(Calendar.DAY_OF_YEAR, -1);
int dayAfter = gc.get(Calendar.DAY_OF_YEAR);
if(dayAfter > dayBefore) {
gc.roll(Calendar.YEAR, -1);
}
gc.get(Calendar.DATE);
java.util.Date yesterday = gc.getTime();
System.out.println("Yesterdays Date = " + sdf.format(yesterday));
}
}
Input Date = 12/12/2003 Yesterdays Date = 12/11/2003
Determine the Day of the Week from Today"s Date
The answer to this question is to use java.util.Calendar.SUNDAY, java.util.Calendar.MONDAY, and so on:
import java.text.ParseException;
public class MainClass {
public static void main(String[] args) throws ParseException {
java.util.Date today = new java.util.Date();
java.sql.Date date = new java.sql.Date(today.getTime());
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.setTime(date);
System.out.println(cal.get(java.util.Calendar.DAY_OF_WEEK));
}
}
ISO ate parsing utility.
/*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* ISO 8601 date parsing utility. Designed for parsing the ISO subset used in
* Dublin Core, RSS 1.0, and Atom.
*
* @author
* @version $Id: ISO8601DateParser.java,v 1.2 2005/06/03 20:25:29 snoopdave Exp $
*/
public class ISO8601DateParser {
// 2004-06-14T19:GMT20:30Z
// 2004-06-20T06:GMT22:01Z
// http://www.cl.cam.ac.uk/~mgk25/iso-time.html
//
// http://www.intertwingly.net/wiki/pie/DateTime
//
// http://www.w3.org/TR/NOTE-datetime
//
// Different standards may need different levels of granularity in the date and
// time, so this profile defines six levels. Standards that reference this
// profile should specify one or more of these granularities. If a given
// standard allows more than one granularity, it should specify the meaning of
// the dates and times with reduced precision, for example, the result of
// comparing two dates with different precisions.
// The formats are as follows. Exactly the components shown here must be
// present, with exactly this punctuation. Note that the "T" appears literally
// in the string, to indicate the beginning of the time element, as specified in
// ISO 8601.
// Year:
// YYYY (eg 1997)
// Year and month:
// YYYY-MM (eg 1997-07)
// Complete date:
// YYYY-MM-DD (eg 1997-07-16)
// Complete date plus hours and minutes:
// YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
// Complete date plus hours, minutes and seconds:
// YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
// Complete date plus hours, minutes, seconds and a decimal fraction of a
// second
// YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
// where:
// YYYY = four-digit year
// MM = two-digit month (01=January, etc.)
// DD = two-digit day of month (01 through 31)
// hh = two digits of hour (00 through 23) (am/pm NOT allowed)
// mm = two digits of minute (00 through 59)
// ss = two digits of second (00 through 59)
// s = one or more digits representing a decimal fraction of a second
// TZD = time zone designator (Z or +hh:mm or -hh:mm)
public static Date parse( String input ) throws java.text.ParseException {
//NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
//things a bit. Before we go on we have to repair this.
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd"T"HH:mm:ssz" );
//this is zero time so we need to add that TZ indicator for
if ( input.endsWith( "Z" ) ) {
input = input.substring( 0, input.length() - 1) + "GMT-00:00";
} else {
int inset = 6;
String s0 = input.substring( 0, input.length() - inset );
String s1 = input.substring( input.length() - inset, input.length() );
input = s0 + "GMT" + s1;
}
return df.parse( input );
}
public static String toString( Date date ) {
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd"T"HH:mm:ssz" );
TimeZone tz = TimeZone.getTimeZone( "UTC" );
df.setTimeZone( tz );
String output = df.format( date );
int inset0 = 9;
int inset1 = 6;
String s0 = output.substring( 0, output.length() - inset0 );
String s1 = output.substring( output.length() - inset1, output.length() );
String result = s0 + s1;
result = result.replaceAll( "UTC", "+00:00" );
return result;
}
}
Obtaining a Date Object From a String
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class MainClass {
public static void main(String[] a) {
Date aDate;
DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
try {
aDate = fmt.parse("Saturday, July 4, 1998 ");
System.out.println("The Date string is: " + fmt.format(aDate));
} catch (java.text.ParseException e) {
System.out.println(e);
}
}
}
The Date string is: Saturday, July 4, 1998
Parses a string representing a date by trying a variety of different parsers.
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>A suite of utilities surrounding the use of the
* {@link java.util.Calendar} and {@link java.util.Date} object.</p>
*
* <p>DateUtils contains a lot of common methods considering manipulations
* of Dates or Calendars. Some methods require some extra explanation.
* The truncate and round methods could be considered the Math.floor(),
* Math.ceil() or Math.round versions for dates
* This way date-fields will be ignored in bottom-up order.
* As a complement to these methods we"ve introduced some fragment-methods.
* With these methods the Date-fields will be ignored in top-down order.
* Since a date without a year is not a valid date, you have to decide in what
* kind of date-field you want your result, for instance milliseconds or days.
* </p>
*
*
*
* @author
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/
public class Main {
//-----------------------------------------------------------------------
/**
* <p>Parses a string representing a date by trying a variety of different parsers.</p>
*
* <p>The parse will try each parse pattern in turn.
* A parse is only deemed sucessful if it parses the whole of the input string.
* If no parse patterns match, a ParseException is thrown.</p>
*
* @param str the date to parse, not null
* @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
* @return the parsed date
* @throws IllegalArgumentException if the date string or pattern array is null
* @throws ParseException if none of the date patterns were suitable
*/
public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
if (str == null || parsePatterns == null) {
throw new IllegalArgumentException("Date and Patterns must not be null");
}
SimpleDateFormat parser = null;
ParsePosition pos = new ParsePosition(0);
for (int i = 0; i < parsePatterns.length; i++) {
if (i == 0) {
parser = new SimpleDateFormat(parsePatterns[0]);
} else {
parser.applyPattern(parsePatterns[i]);
}
pos.setIndex(0);
Date date = parser.parse(str, pos);
if (date != null && pos.getIndex() == str.length()) {
return date;
}
}
throw new ParseException("Unable to parse the date: " + str, -1);
}
}
Perform date validations
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* <p>Perform date validations.</p>
* <p>
* This class is a Singleton; you can retrieve the instance via the
* getInstance() method.
* </p>
*
* @version $Revision: 478334 $ $Date: 2006-11-22 21:31:54 +0000 (Wed, 22 Nov 2006) $
* @since Validator 1.1
*/
public class DateValidator {
/**
* Singleton instance of this class.
*/
private static final DateValidator DATE_VALIDATOR = new DateValidator();
/**
* Returns the Singleton instance of this validator.
* @return A singleton instance of the DateValidator.
*/
public static DateValidator getInstance() {
return DATE_VALIDATOR;
}
/**
* Protected constructor for subclasses to use.
*/
protected DateValidator() {
super();
}
/**
* <p>Checks if the field is a valid date. The pattern is used with
* <code>java.text.SimpleDateFormat</code>. If strict is true, then the
* length will be checked so "2/12/1999" will not pass validation with
* the format "MM/dd/yyyy" because the month isn"t two digits.
* The setLenient method is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
* @param strict Whether or not to have an exact match of the datePattern.
* @return true if the date is valid.
*/
public boolean isValid(String value, String datePattern, boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.length() <= 0) {
return false;
}
SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
if (strict && (datePattern.length() != value.length())) {
return false;
}
return true;
}
/**
* <p>Checks if the field is a valid date. The <code>Locale</code> is
* used with <code>java.text.DateFormat</code>. The setLenient method
* is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, defaults to the default
* system default if null.
* @return true if the date is valid.
*/
public boolean isValid(String value, Locale locale) {
if (value == null) {
return false;
}
DateFormat formatter = null;
if (locale != null) {
formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
} else {
formatter =
DateFormat.getDateInstance(
DateFormat.SHORT,
Locale.getDefault());
}
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
return true;
}
}
Show date and time using only Date methods.
import java.util.Date;
class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date);
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
}
}
The java.util.Date Class
- java.util.Date, a class normally used to represent dates and times.
- java.util.Calendar, often used to manipulate dates.
Times can also be represented as a long. See the discussion of the currentTimeMillis method of the java.lang.System
public Date ()
public Date (long time)
Tue Jan 13 12:38:31 PST 1970