7

I need to convert javascript date to Carbon date. i want to filter records by month and year Only.

 $date  = Javascript Date to Carbon Date? 
 $logs =  $logs->whereBetween('created_at', [$date->startOfMonth(), $date->endOfMonth()]); 

Thanks in Advance.

1
  • Can you provide sample input data and possible error messages that were given by any attempt you've tried so far? Please edit your question to contain such information
    – Nico Haase
    Jan 21, 2019 at 11:01

3 Answers 3

7

Hard to guess without the JS date output but you can try with

Carbon::parse($date);

If it fails you need to format you JS date and then use

Carbon::createFromFormat('Y-m-d H:i:s', $date);
4
  • Mon Jan 21 2019 16:07:31 GMT+0530 (India Standard Time) js Date Format
    – Neha
    Jan 21, 2019 at 10:37
  • getting error with above code "DateTime::__construct(): Failed to parse time string (stpm31 Jpm1 01 2011 00:00:00 16JanIST+0530 (012108pm st31pm121pmMon, 21 Jan 2019 16:08:37 +053021 IST0801Asia/Kolkata)) at position 0 (s): The timezone could not be found in the database"
    – Neha
    Jan 21, 2019 at 10:39
  • Is this the JS output ? what the error ? You try to dd() in your controller ? what output ?
    – lovis91
    Jan 21, 2019 at 10:40
  • yes i tried to add dd. And the error is Failed to parse time string (stpm31 Jpm1 01 2011 00:00:00 16JanIST+0530 (012108pm st31pm121pmMon, 21 Jan 2019 16:08:37 +053021 IST0801Asia/Kolkata)) at position 0 (s)
    – Neha
    Jan 21, 2019 at 10:45
1

You can use this approach where new Date() is like Sat Aug 24 2019 20:36:26 GMT+0600 (Bangladesh Standard Time)

first use following JavaScript function for parsing new Date()

   function datefilter(date){
            let month = date.getMonth();
            let year = date.getFullYear();
            let day = date.getDate();
            return day+'-'+month + '-' + year;
    }
    datafilter(new Date());

The output will be "24-7-2019"

then use Carbon createFromFormate like

Carbon::createFromFormat('d-m-Y', $data['enddate']);

I guess output will remain to same"24-7-2019"

1

Firstly convert js Date into d-m-y or y-m-d

var date = new Date();let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" +current_datetime.getFullYear();

Now convert date into carbon date:

    Carbon\Carbon::createFromFormat('d-m-Y', $date);
or 
    Carbon\Carbon::createFromFormat('Y-m-d', $date);

// your formatted date format here createFromFormat(formatted_date_format, $date);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.