itsource

Java 값을 사용하여 날짜 개체를 만드는 방법

mycopycode 2022. 11. 26. 14:01
반응형

Java 값을 사용하여 날짜 개체를 만드는 방법

2014년 2월 11일 날짜 오브젝트가 필요합니다.이렇게 직접 만들 수는 없지만

Date myDate = new Date(2014, 02, 11);

그래서 저는 이렇게 하고 있어요.

Calendar myCalendar = new GregorianCalendar(2014, 2, 11);
Date myDate = myCalendar.getTime();

java에서 date 객체를 쉽게 작성할 수 있는 방법이 있나요?

Gotcha: 2를 월로 전달하면 예기치 않은 결과가 발생할 수 있습니다.Calendar API에서 월은 0을 기준으로 합니다.2는 사실 3월을 의미합니다.

캘린더를 사용하는 것은 이미 간단하다고 생각하기 때문에, 당신이 찾고 있는 「간단한」 방법이 무엇인지 모르겠습니다.

월에 올바른 상수를 사용해야 합니다.

 Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();

또 다른 방법은 DateFormat을 사용하는 것입니다.이것들은 보통 다음과 같은 유틸리티를 가지고 있습니다.

 public static Date parseDate(String date) {
     try {
         return new SimpleDateFormat("yyyy-MM-dd").parse(date);
     } catch (ParseException e) {
         return null;
     }
  }

간단하게 쓸 수 있도록

Date myDate = parseDate("2014-02-14");

제가 또 다른 은 '보다 낫다'입니다.Java Date/Calendar 。JODA 시간 Java 시간(JSR310, JDK 8+)입니다.하시면 됩니다.LocalDate

LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);

dr;dr

LocalDate.of( 2014 , 2 , 11 )

옛날의 java.util.Dateclass, 최신 java.time 클래스에서 변환합니다.

java.util.Date                        // Terrible old legacy class, avoid using. Represents a moment in UTC. 
.from(                                // New conversion method added to old classes for converting between legacy classes and modern classes.
    LocalDate                         // Represents a date-only value, without time-of-day and without time zone.
    .of( 2014 , 2 , 11 )              // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
    .atStartOfDay(                    // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
        ZoneId.of( "Africa/Tunis" )   // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`. 
    )                                 // Returns a `ZonedDateTime`.
    .toInstant()                      // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
)                                     // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.   

세부 사항

"쉬운"을 원한다면 문제가 많은 java.util이 아닌 Java 8의 새로운 java.time 패키지를 사용해야 합니다.Java에 번들된 Date & .Calendar 클래스.

java.time

Java 8 이후에 내장된 java.time 프레임워크는 문제가 되는 오래된 java.util을 대체합니다.Date/.Calendar 클래스

날짜만

여기에 이미지 설명 입력

클래스는 java.time에 의해 제공되며 시간대나 시간대가 없는 날짜 전용 값을 나타냅니다.예를 들어 파리에서는 새로운 날이 몽트렐보다 더 일찍 시작되므로 날짜를 결정하려면 표준 시간대가 필요합니다.그 수업은 표준 시간대를 위한 것이다.

ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );

콘솔로 덤프:

System.out.println ( "today: " + today + " in zone: " + zoneId );

오늘: 2015-11-26 구역:아시아/싱가포르

또는 공장 방법을 사용하여 년, 월, 날짜를 지정합니다.

LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );

local Date: 2014-02-11

1~12가 1~합니다.DayOfWeekobject.enum " "

LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );

시간대

여기에 이미지 설명 입력

A LocalDate시간대로 조정하기 전까지는 진정한 의미가 없습니다.하여 java.time을 합니다.ZonedDateTime시죠?것도시시시미미미미미,,,,?시간이라고 있습니다.00:00:00.000단, Daylight Saving Time(DST; 일광 절약 시간) 및 기타 이상 징후 때문에 항상 해당되는 것은 아닙니다.그 시간을 상정하는 대신 호출을 통해 java.time에 하루 중 첫 번째 순간을 결정하도록 요청합니다.

다음 형식으로 적절한 시간대 이름을 지정합니다.continent/region, , , 등Pacific/Auckland EST ★★★★★★★★★★★★★★★★★」IST이는 진정한 표준 시간대가 아니며 표준화되지 않았으며 고유하지도 않기 때문입니다(!).

ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

zdt: 2014-02-11T00:00+08:00[아시아/싱가포르]

UTC

여기에 이미지 설명 입력

백엔드 작업(비즈니스 로직, 데이터베이스, 데이터 스토리지 및 교환)에는 보통 UTC 시간대를 사용합니다.java.time에서 클래스는 타임라인상의 순간을 UTC로 나타냅니다.Instant 객체는 를 호출하여 ZonedDateTime에서 추출할 수 있습니다.

Instant instant = zdt.toInstant();

즉석 : 2014-02-10T16:00Z

변환

'어울릴 수 없다'는 사용하지 않는 이 좋습니다.java.util.Date수업 전체를.그러나 java.time용으로 아직 업데이트되지 않은 오래된 코드와 상호 운용해야 하는 경우에는 앞뒤로 변환할 수 있습니다.이전 클래스에 추가된 새로운 변환 메서드를 살펴봅니다.

java.util.Date d = java.util.from( instant ) ;

…그리고…

Instant instant = d.toInstant() ;

Java의 모든 날짜 유형(현대 및 레거시) 표


java.time 정보

java.time 프레임워크는 Java 8 이후에 포함되어 있습니다.이러한 클래스는 , 및 등 문제가 많은 오래된 레거시 날짜 시간 클래스를 대체합니다.

자세한 내용은 Oracle 자습서를 참조하십시오.또한 Stack Overflow를 검색하여 많은 예와 설명을 확인하십시오.사양은 JSR 310입니다.

현재 유지보수 모드에 있는 조다 타임 프로젝트는 java.time 클래스로의 이행을 권장합니다.

java.time 객체를 데이터베이스와 직접 교환할 수 있습니다.JDBC 4.2 이후준거한JDBC 드라이버를 사용합니다.스트링도 필요 없고java.sql.*반.휴지 상태 5 및 JPA 2.2는 java.time을 지원합니다.

java.time 클래스는 어디서 얻을 수 있습니까?


업데이트: Joda-Time 라이브러리가 유지보수 모드로 전환되었으며 java.time 클래스로의 이행을 권장합니다.역사를 위해 이 섹션을 남겨두겠습니다.

조다 타임

우선 Joda-Time은 합리적인 번호를 사용하므로 2월은2것은 아니다.1Joda-Time DateTime은 java.util과 달리 할당된 시간대를 정확히 알고 있습니다.표준 시간대가 있는 것처럼 보이지만 없는 날짜.

그리고 시간대를 잊지 마세요.그렇지 않으면 JVM의 기본값이 됩니다.

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );

java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );

콘솔에 덤프...

System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );

실행 시...

dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT

변환

java.util로 변환할 필요가 있는 경우.다른 클래스와 함께 사용하는 날짜...

java.util.Date date = dateTimeSingapore.toDate();

제 생각에 가장 좋은 방법은 이 버젼을 사용하는 것입니다.SimpleDateFormat물건.

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here

Java8부터:

import java.time.Instant;
import java.util.Date;

Date date = Date.from(Instant.parse("2000-01-01T00:00:00.000Z"))

이거 드셔보세요

 Calendar cal = Calendar.getInstance();
    Date todayDate = new Date();
    cal.setTime(todayDate);

    // Set time fields to zero
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    todayDate = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want

try {
    String dateStart = "June 14 2018 16:02:37";
    cal.setTime(sdf.parse(dateStart));
    //all done
} catch (ParseException e) {
    e.printStackTrace();
}

가장 간단한 방법:

Date date = Date.valueOf("2000-1-1");
LocalDate localdate = LocalDate.of(2000,1,1);
LocalDateTime localDateTime = LocalDateTime.of(2000,1,1,0,0);
import java.io.*;
import java.util.*;
import java.util.HashMap;

public class Solution 
{

    public static void main(String[] args)
    {
        HashMap<Integer,String> hm = new HashMap<Integer,String>();
        hm.put(1,"SUNDAY");
        hm.put(2,"MONDAY");
        hm.put(3,"TUESDAY");
        hm.put(4,"WEDNESDAY");
        hm.put(5,"THURSDAY");
        hm.put(6,"FRIDAY");
        hm.put(7,"SATURDAY");
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();

        String format = year + "/" + month + "/" + day;
        Date date = null;
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            date = formatter.parse(format);
        }
        catch(Exception e){
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(hm.get(dayOfWeek));
    }
}

당신의 날짜는 php에서 html(dom)로 작성되어 있는 것 같습니다.모든 날짜와 타임스탬프를 준비하기 위한 php-함수가 있습니다.이렇게 하면 필요한 대형이 반환됩니다.

$timeForJS = timeop($datetimeFromDatabase['payedon'], 'js', 'local'); // save 10/12/2016 09:20 on var

js에서 이 형식을 사용하여 새 날짜...를 만들 수 있습니다.

<html>
   <span id="test" data-date="<?php echo $timeForJS; ?>"></span>
   <script>var myDate = new Date( $('#test').attr('data-date') );</script>
</html>

내가 말하고자 하는 것은, 당신만의 기능을 포장해서 당신의 삶을 더 편하게 만들라는 것이다.my func를 샘플로 사용할 수 있지만, my cms에 포함되어 있기 때문에 복사하여 1대 1로 붙여넣을 수 없습니다.

    function timeop($utcTime, $for, $tz_output = 'system')
{
    // echo "<br>Current time ( UTC ): ".$wwm->timeop('now', 'db', 'system');
    // echo "<br>Current time (USER): ".$wwm->timeop('now', 'db', 'local');
    // echo "<br>Current time (USER): ".$wwm->timeop('now', 'D d M Y H:i:s', 'local');
    // echo "<br>Current time with user lang (USER): ".$wwm->timeop('now', 'datetimes', 'local');

    // echo '<br><br>Calculator test is users timezone difference != 0! Tested with "2014-06-27 07:46:09"<br>';
    // echo "<br>Old time (USER -> UTC): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'system');
    // echo "<br>Old time (UTC -> USER): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'local');

    /** -- */
    // echo '<br><br>a Time from db if same with user time?<br>';
    // echo "<br>db-time (2019-06-27 07:46:09) time left = ".$wwm->timeleft('2019-06-27 07:46:09', 'max');
    // echo "<br>db-time (2014-06-27 07:46:09) time left = ".$wwm->timeleft('2014-06-27 07:46:09', 'max', 'txt');

    /** -- */
    // echo '<br><br>Calculator test with other formats<br>';
    // echo "<br>2014/06/27 07:46:09: ".$wwm->ntimeop('2014/06/27 07:46:09', 'db', 'system');

    switch($tz_output){
        case 'system':
            $tz = 'UTC';
            break;

        case 'local':
            $tz = $_SESSION['wwm']['sett']['tz'];
            break;

        default:
            $tz = $tz_output;
            break;
    }

    $date = new DateTime($utcTime,  new DateTimeZone($tz));

    if( $tz != 'UTC' ) // Only time converted into different time zone
    {
        // now check at first the difference in seconds
        $offset = $this->tz_offset($tz);
        if( $offset != 0 ){
            $calc = ( $offset >= 0  ) ? 'add' : 'sub';
            // $calc = ( ($_SESSION['wwm']['sett']['tzdiff'] >= 0 AND $tz_output == 'user') OR ($_SESSION['wwm']['sett']['tzdiff'] <= 0 AND $tz_output == 'local') ) ? 'sub' : 'add';
            $offset = ['math' => $calc, 'diff' => abs($offset)];
            $date->$offset['math']( new DateInterval('PT'.$offset['diff'].'S') ); // php >= 5.3 use add() or sub()
        }
    }

    // create a individual output
    switch( $for ){
        case 'js':
            $format = 'm/d/Y H:i'; // Timepicker use only this format m/d/Y H:i without seconds // Sett automatical seconds default to 00
            break;
        case 'js:s':
            $format = 'm/d/Y H:i:s'; // Timepicker use only this format m/d/Y H:i:s with Seconds
            break;
        case 'db':
            $format = 'Y-m-d H:i:s'; // Database use only this format Y-m-d H:i:s
            break;
        case 'date':
        case 'datetime':
        case 'datetimes':
            $format = wwmSystem::$languages[$_SESSION['wwm']['sett']['isolang']][$for.'_format']; // language spezific output
            break;
        default:
            $format = $for;
            break;
    }

    $output = $date->format( $format );

    /** Replacement
     * 
     * D = day short name
     * l = day long name
     * F = month long name
     * M = month short name
     */
    $output = str_replace([
        $date->format('D'),
        $date->format('l'),
        $date->format('F'),
        $date->format('M')
    ],[
        $this->trans('date', $date->format('D')),
        $this->trans('date', $date->format('l')),
        $this->trans('date', $date->format('F')),
        $this->trans('date', $date->format('M'))
    ], $output);

    return $output; // $output->getTimestamp();
}

언급URL : https://stackoverflow.com/questions/22326339/how-create-date-object-with-values-in-java

반응형