Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery datepicker and php datetime don't agree?

I'm trying to do something that seems like it should be simple, but somehow won't tie up properly.

The user selects a date from a jquery datepicker, where I have showWeek enabled.

$(".datepicker").datepicker({
    showWeek: true,
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd'
});

But, when the resulting date string is fed into a php datetime, the week does not correspond, and is 1 week further into the future.

$start_date = isset($_POST['startdate']) ? $_POST['startdate'] : "";
$start = new DateTime($start_date);
echo $start->format("W"); 

IE, 2018-10-02 shows as week 39 in my datepicker, but the echo above from reading that date back into a datetime and formatting for week returns week 40.

So, as far as I can tell, the jquery datepicker and php datetime class do not agree on which weeks are which by default.

Is there a way to reconcile this?

The PHP date says it conforms to ISO-8601, Checking online confirms for me that php has it right, so how do I fix the datepicker to display correctly?

like image 566
ErosRising Avatar asked Oct 03 '18 07:10

ErosRising


1 Answers

Ok here is the solution: according to jquery ui you need to specify the first day and in your code you are missing it:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Show week of the year</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker({
      showWeek: true,
      firstDay: 1,
      changeMonth: true,
      changeYear: true,
      dateFormat: 'yy-mm-dd'
    });
  } );
  </script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
 
 
</body>

Just add firstDay: 1, and everything works as you expect.

like image 116
Sigma Avatar answered Nov 07 '22 17:11

Sigma