programing

문자열을 카본으로 변환

goodjava 2023. 2. 3. 20:10

문자열을 카본으로 변환

Larabel 5.1을 사용하고 있습니다.

며칠 전에 저는protected $dates = ['license_expire']문자열 날짜를 Carbon 인스턴스로 변환합니다.HTML에서 날짜 작성 양식의 기본값은 다음과 같습니다.Carbon\Carbon::now()->format('Y-m-d')

내가 사용한 홈페이지에서 경고를 표시하기 위해<p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>

그때까지 diffForHumans() 메서드는 정상적으로 동작합니다.

그러나 이 경우 편집 양식의 기본값은 데이터베이스에 무엇이 있든 상관없이 오늘 날짜이기도 합니다(부분 양식을 사용 중입니다).이를 해결하기 위해 HTML의 기본값을 NLL로 변경합니다.그리고 내 모델에 다른 방법을 추가하여 현재 날짜를 생성 형식으로 표시합니다.

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date)->format('Y-m-d');
}

그 후 홈페이지에 들어가면FatalErrorException말하자면Call to a member function diffForHumans() on string

날짜를 확인해보니dd($employee->license_expire)다시 STRING이 됩니다.

이 상황에서 어떻게 문자열을 카본으로 변환할 수 있는지 알려 주실 수 있나요?

또는

작성 폼의 기본 날짜를 오늘 날짜로, 편집 폼의 날짜를 데이터베이스에서 만들고 diffForHumans()를 사용하여 홈페이지에 경고를 표시할 수 있습니까?

거의 다 왔어.

제거한다.protected $dates = ['license_expire']

그 후, 변경해당LicenseExpire접근자:

public function getLicenseExpireAttribute($date)
{
    return Carbon::parse($date);
}

이 방법을 사용하면,Carbon어떤 일이 있어도.그래서 당신의 폼을 위해서$employee->license_expire->format('Y-m-d')(또는 필요한 형식에 관계없이) 및diffForHumans()홈 페이지에서도 사용할 수 있습니다.


Larabel 9+ 를 사용하고 있는 경우는, 갱신된 구문을 사용해 Accessor 를 정의할 수도 있습니다.

use Illuminate\Database\Eloquent\Casts\Attribute;

public function licenseExpire(): Attribute 
{
    return Attribute::make(
        get: fn ($value) => Carbon::parse($value);
    );
}

다음을 사용해 보십시오.

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

$filter['date Of Service']= '06.2021';

$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');

이거 드셔보세요

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

언급URL : https://stackoverflow.com/questions/32549221/convert-string-to-carbon