茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1670173 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
F09_267.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

爪哇咖啡屋 : [分享]Java 取得現在的日期、時間

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[分享]Java 取得現在的日期、時間
取得現在的日期、時間
GET DATE & TIME in java

import java.util.Calendar;
import java.text.SimpleDateFormat;

public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

public static String now() {
			 Calendar tmpCal = Calendar.getInstance();
			 SimpleDateFormat tmpSDF = new SimpleDateFormat(DATE_FORMAT_NOW);
			 return tmpSDF.format(tmpCal.getTime();
}


如果需要改格式的話,就把『DATE_FORMAT_NOW』的內容改過來就好了!

LetterDate or Time ComponentExamples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Java日期計算月是(0~11)

Java日期計算月是(0~11)

每次寫程式都忘記,假如用Calendar來計算日期的時候

月份要帶進去0~11而不是,1~12月

所以按照下方程式的邏輯帶進去theday.set的月要先減1,然後輸出時再加回去

 

public String changeDate(String SourceDate,int d){
String Yesterday = "";

Calendar theday = Calendar.getInstance() ;
SourceDate = SourceDate.trim();
theday.set( Integer.parseInt(SourceDate.substring(0,4)),Integer.parseInt(SourceDate.substring(4,6)) -1,Integer.parseInt(SourceDate.substring(6,8)));


theday.add(Calendar.DATE,d);

int sYear = theday.get(Calendar.YEAR);
int sMonth = theday.get(Calendar.MONTH) + 1;

int sDay = theday.get(Calendar.DATE );
 
 DecimalFormat datedf = new DecimalFormat("00");
 String datted = String.valueOf(sYear) +  datedf.format(sMonth) + datedf.format(sDay);
 return datted;
}


原文出處: Java日期計算月是(0~11) @ ROACH部落落 :: 痞客邦 PIXNET ::
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]How to get the current date/time in java [duplicate]
How to get the current date/time in java [duplicate]

Equivalent of C#'s DateTime.Now in Java? 10 answers

--------------------------------------------------------------------------------

It depends on what form of date / time you want:

If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.

If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.

new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here.

in Java 8, calling LocalDateTime.now() and ZonedDateTime.now() will give you representations for the current date / time.

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations. With Java 8, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong reason to migrate.

--------------------------------------------------------------------------------

If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());


--------------------------------------------------------------------------------

If you want the current date as String, try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

--------------------------------------------------------------------------------

Just create a Date object...
Date date = new Date();


--------------------------------------------------------------------------------

In Java 8 it is:
LocalDateTime.now()

and in case you need time zone info:
ZonedDateTime.now()

and in case you want to print fancy formatted string:
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))

    // 2015/09/27 15:07:53
    System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 15:07:53
    System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 09/28/2015
    System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));

    // 20150928_161823
    System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );

    // Mon Sep 28 16:24:28 CEST 2015
    System.out.println( Calendar.getInstance().getTime() );

    // Mon Sep 28 16:24:51 CEST 2015
    System.out.println( new Date(System.currentTimeMillis()) );

    // Mon Sep 28
    System.out.println( new Date().toString().substring(0, 10) );

    // 2015-09-28
    System.out.println( new java.sql.Date(System.currentTimeMillis()) );

    // 14:32:26
    Date d = new Date();
    System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );

    // 2015-09-28 17:12:35.584
    System.out.println( new Timestamp(System.currentTimeMillis()) );

    // Java 8

    // 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
    System.out.println( ZonedDateTime.now() );

    // Mon, 28 Sep 2015 16:16:23 +0200
    System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );

    // 2015-09-28
    System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class

    // 16
    System.out.println( LocalTime.now().getHour() );

    // 2015-09-28T16:16:23.315
    System.out.println( LocalDateTime.now() );

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );


--------------------------------------------------------------------------------

There are many different methods:

System.currentTimeMillis()
Date
Calendar

--------------------------------------------------------------------------------

Have you looked at java.util.Date? It is exactly what you want.

--------------------------------------------------------------------------------

Create object of date and simply print it down.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);


--------------------------------------------------------------------------------
java.util.Date date = new java.util.Date();

It's automatically populated with the time it's instantiated.

--------------------------------------------------------------------------------

I find this the best way :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22


--------------------------------------------------------------------------------

1.1 How to obtain current Date
import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date(); // date object
  System.out.println(date); // try to print the date object
 }
}

1.2 How to use getTime() method
import java.util.Date;
public class Main {
    public static void main(String[]args){
        Date date =new Date();
        long timeInMilliSeconds=date.getTime();
        System.out.println(timeInMilliSeconds);
    }
}

this will return the number of milliseconds since January 1, 1970, 00:00:00 GMT for time comparison purposes.

1.3 How to format time using SimpleDateFormat class
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date();
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
  String formattedDate=dateFormat.format(date);
  System.out.println(formattedDate);
 }
}

Also try using different format patterns like "yyyy-MM-dd hh:mm:ss" and select desired pattern. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

2nd Understand the java.util.Calendar class

2.1 Using Calendar Class to obtain current time stamp
import java.util.Calendar;
class Demostration{
 public static void main(String[]args){
  Calendar calendar=Calendar.getInstance();
  System.out.println(calendar.getTime());
 }
}

2.2 Try using setTime and other set methods for set calendar to different date.

source: http://javau91.blogspot.com/

--------------------------------------------------------------------------------

Have a look at the Date class. There's also the newer Calendar class which is the preferred method of doing many date / time operations (a lot of the methods on Date have been deprecated.)

If you just want the current date, then either create a new Date object or call Calendar.getInstance();.

--------------------------------------------------------------------------------

As mentioned the basic Date() can do what you need in terms of getting the current time. In my recent experience working heavily with Java dates there are a lot of oddities with the built in classes (as well as deprecation of many of the Date class methods). One oddity that stood out to me was that months are 0 index based which from a technical standpoint makes sense, but in real terms can be very confusing.

If you are only concerned with the current date that should suffice - however if you intend to do a lot of manipulating/calculations with dates it could be very beneficial to use a third party library (so many exist because many Java developers have been unsatisfied with the built in functionality).

I second Stephen C's recommendation as I have found Joda-time to be very useful in simplifying my work with dates, it is also very well documented and you can find many useful examples throughout the web. I even ended up writing a static wrapper class (as DateUtils) which I use to consolidate and simplify all of my common date manipulation.

--------------------------------------------------------------------------------

SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));

the print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.

--------------------------------------------------------------------------------

tl;dr
Instant.now()

… or …
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )

java.time

A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.
Time zone

The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.
Instant

Much of your business logic and data storage/exchange should be done in UTC, as a best practice. To get the current moment in UTC with a resolution in nanoseconds, use Instant class.
Instant instant = Instant.now();

ZonedDateTime

You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

We can skip the Instant and get the current ZonedDateTime directly.
ZonedDateTime zdt = ZonedDateTime.now( z );

Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.

You can later extract an Instant from the ZonedDateTime.
Instant instant = zdt.toInstant();

Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local… types into a ZonedDateTime and thereby make it meaningful.
LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );  // Always pass a time zone.

Strings

To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.
    String output = myLocalDate.toString();  // 2016-09-23

… or …
String output = zdt.toString();  // 2016-09-23T12:34:56.789+03:00[America/Montreal]

The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.

For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.
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.

--------------------------------------------------------------------------------

import java.util.*;

import java.text.*;

public class DateDemo { public static void main(String args[]) {

  Date dNow = new Date( );
  SimpleDateFormat ft =
  new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

  System.out.println("Current Date: " + ft.format(dNow));

} }

you can use date for fet currunt data. so using SimpleDateFormat get format

原文出處:datetime - How to get the current date/time in java - Stack Overflow
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Java – How to get current date time – date() and calender()
Java – How to get current date time – date() and calender()

By mkyong | December 24, 2009 | Updated : August 6, 2014 | Viewed : 1,965,056 times +8,288 pv/w

In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into a user friendly format.
1. Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48

2. Calender() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22

Review a full example to show you how to use Date() and Calender() classes to get and display the current date time.
GetCurrentDateTime.java

package com.mkyong;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GetCurrentDateTime {
  public static void main(String[] args) {

	   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	   //get current date time with Date()
	   Date date = new Date();
	   System.out.println(dateFormat.format(date));

	   //get current date time with Calendar()
	   Calendar cal = Calendar.getInstance();
	   System.out.println(dateFormat.format(cal.getTime()));

  }
}

Output
2014/08/06 16:06:54
2014/08/06 16:06:54

References

Date JavaDoc
Calendar JavaDoc
SimpleDateFormat JavaDoc

原文出處:https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/">Java – How to get current date time – date() and calender()
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|