nkdAgility / NKDAgility.com

0 stars 0 forks source link

Timezone Convertor #8

Open MrHinsh opened 1 week ago

MrHinsh commented 1 week ago

Implementation from PHP site:

function nkdagility_timezone_header(){
?>
<script type="text/javascript" src="https://momentjs.com/downloads/moment.js"></script>
<script type="text/javascript" src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script type="text/javascript" src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.7/jstz.min.js"></script>

<script type="text/javascript">
  function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  function setSelectedTimezone(timezone) {
    setCookie("selectedTimeZone", timezone, 10);
    //alert("Cookie set to: " + timezone);   
    timezoneGigomatic();
  }

  function getSelectedTimezone() {
    //alert(selectedTimezone);
    var selectedTimezone= getCookie("selectedTimeZone");
    if (selectedTimezone === null || selectedTimezone.trim() === "") {
      var tz = jstz.determine();
      setCookie("selectedTimeZone", tz.name(), 10);
      selectedTimezone = tz.name();
    }
    //alert(selectedTimezone);
    return selectedTimezone;
  }  

  function timezoneGigomatic() {
    //alert("fixin the dates");
    var timezone = getSelectedTimezone();
    moment.locale('en');
    //Fix Time
    document.querySelectorAll('[nkddata-toggle="timezoneGigomatic"]').forEach(function(element) {
      //alert(timezone);
      var startDate = element.getAttribute("nkddata-start");
      var endDate = element.getAttribute("nkddata-end");
      var timeZoneOfClass = element.getAttribute("nkddata-tz");
      var timeZoneFormat = element.getAttribute("nkddata-format");
      var outMode = element.getAttribute("nkddata-output");     
      var startMoment = new moment(startDate);
      var endMoment = new moment(endDate);
      var output = "";
      switch(outMode)
      {
        case "time":
          output = startMoment.tz(timezone).format('HH:mm') + "-" + endMoment.tz(timezone).format('HH:mm') + " " + startMoment.tz(timezone).format('z');
          break;
        case "date":
          //Statement or expression;
          output = "";
          output = output + startMoment.tz(timezone).format('D')
          if (startMoment.tz(timezone).format('MM') != endMoment.tz(timezone).format('MM'))
          {
            output = output +" ";
            output = output + startMoment.tz(timezone).format('MMM')
          }
          if (startMoment.tz(timezone).format('D') != endMoment.tz(timezone).format('D'))
          {
            output = output + "-";
            output = output + endMoment.tz(timezone).format('D');
          }
          output = output +" ";
          output = output +  endMoment.tz(timezone).format('MMM');
          output = output +", ";
          output = output + endMoment.tz(timezone).format('YYYY');
          break;
        case "dateStart":
          output = startMoment.tz(timezone).format('Do MMMM YYYY')
          break;
        case "dateEnd":
          output = endMoment.tz(timezone).format('Do MMMM YYYY')
          break;
        default:
          //default statement or expression;
          output = "what is this?";
      }
      element.innerHTML = output;
    });

  }

</script>
<style>

</style>
<?php
};

function nkdagility_timezone_footer(){
?>
<script>
    timezoneGigomatic();

    jQuery( document ).on( 'js_event_wpv_parametric_search_results_updated', function( event, data ) {
        /**
            * data.view_unique_id (string) The View unique ID hash
            * data.layout (object) The jQuery object for the View layout wrapper
            */
        //alert("js_event_wpv_parametric_search_results_updated");
        timezoneGigomatic();
    });

    jQuery( document ).on( 'js_event_wpv_pagination_completed', function( event, data ) {
        /**
                * data.view_unique_id (string) The View unique ID hash
                * data.effect (string) The View AJAX pagination effect
                * data.speed (integer) The View AJAX pagination speed in miliseconds
                * data.layout (object) The jQuery object for the View layout wrapper
                */
        //alert("js_event_wpv_pagination_completed");
        timezoneGigomatic();
    });

</script>
<?php
};

function nkdAgilityTimeZoneFOrmater()
{
  $dt = new DateTime();
  $dt->setTimestamp($timestamp);
  $dateSrc = $dt->format('Y-m-d H:i:s');  
  $ClassDateTime = new DateTime($dateSrc, new DateTimeZone($classtimezone));

  $ClassDateTime->setTimezone(new DateTimeZone($timezone));
  return $ClassDateTime->format($format);
}

function nkdagilitytimeviewer($params, $content = null) {
  // default parameters
  $args = shortcode_atts(array(
    'wrap' => 1,
    'debug' => 0,
    'outmode' => 'time'
  ), $params);

    $wrap = (int) $args['wrap'];
    $debug = (int) $args['debug'];
    $outmode = (string) $args['outmode'];

     $outdebug .= $outmode;
    $post = get_post();
    if ( empty( $post )) {
     $outdebug .= " postempty ";
    }
    $outhtml = $outhtml .$post->ID;
    $trainingTimezoneText = get_post_meta( $post->ID, 'wpcf-training-timezone', true );
    $outhtml .= $trainingTimezoneText;
    $trainingTimezone = timezone_open($trainingTimezoneText);
    $trainingStartDateText = do_shortcode('[types field="event-date" style="text" format="Y-m-d H:i:s"][/types]');
    $outhtml .= $trainingStartDateText;
    $trainingStartdate = new DateTimeImmutable($trainingStartDateText, $trainingTimezone);

   $trainingEndDateText = do_shortcode('[types field="event-end-date" style="text" format="Y-m-d H:i:s"][/types]');
   $trainingEndDate  = new DateTimeImmutable($trainingEndDateText, $trainingTimezone);

   $outputText = "";

   switch ($outmode) 
   {
     case "time":
       $outputText = ""
         .date_format($trainingStartdate,"H:i")
         ."-"
         .date_format($trainingEndDate,"H:i")
         ." "
         .date_format($trainingStartdate,"T");
       break;
     case "date":
       $outputText = date_format($trainingStartdate,"j");
       if (date_format($trainingStartdate,"F") != date_format($trainingEndDate,"F"))
       {
         $outputText .= " ";
         $outputText .= date_format($trainingStartdate,"M");
       }
       if (date_format($trainingStartdate,"j") != date_format($trainingEndDate,"j"))
       {
         $outputText .= "-";
         $outputText .= date_format($trainingEndDate,"j");
       }
       $outputText .= " ";
       $outputText .= date_format($trainingStartdate,"M");
       $outputText .= ", ";
       $outputText .= date_format($trainingStartdate,"Y");
       break;
     case "dateStart":
       $outputText = date_format($trainingStartdate,"jS F Y");
       break;
     case "dateEnd":
       $outputText = date_format($trainingEndDate,"jS F Y");
       break;
   }     

   $outhtml =  "<span nkddata-toggle='timezoneGigomatic' "
     ."nkddata-start='" .$trainingStartdate->format('c') ."' "
     ."nkddata-end='" .$trainingEndDate->format('c') ."' "
     ."nkddata-tz='" .$trainingTimezoneText ."' "
     ."nkddata-output='" .$outmode ."' "
     ."title='Original " .$outmode ." " .$outputText ." (" .$trainingTimezoneText .")" ."'>"
     .$outputText
     ."</span>";
    if ($debug == 1)
    {
    $outhtml .= "<span title='" .$outdebug ."'> [debug] </span>";
    }
  return $outhtml;  
}

function nkdagilitytimezoneselector($params, $content = null) {
  // default parameters
  extract(shortcode_atts(array(
    'wrap' => 1,
    'debug' => 1
  ), $params));

  //$commonTimezones = array("Europe/London", "America/New_York", "America/Chicago", "America/Los_Angeles");
  //rt($commonTimezones);

  $timezone_identifiers = timezone_identifiers_list();

  $selecthtml = "<div class='d-flex flex-row mb-1'>";
  $selecthtml .= "<div class='p-1'>";
  $selecthtml .=  "<select id='nkdagilitytimezoneselector' name='nkdagilitytimezoneselector' onchange='setSelectedTimezone(this.value)' class='form-select form-select-sm'><option disabled selected>--select timezone--</option>";
     foreach( $timezone_identifiers as $identifier ) {
         $selecthtml .='<option value="'.$identifier.'"';
         $selecthtml .= '>'.$identifier.'</option>';
    }
  $selecthtml .= "</select>";
  $selecthtml .= "</div>";
  $selecthtml .= "<div class='p-1'>";
  $selecthtml .= "<a class='btn btn-link btn-sm' onclick='setCookie(\"selectedTimeZone\", null, -10);document.getElementById(\"nkdagilitytimezoneselector\").value=getSelectedTimezone();timezoneGigomatic();' title='Reset to your detected timezone'>reset</a>";
  $selecthtml .= "</div>";
  $selecthtml .= "</div>";
  $selecthtml .=  "<script>";
  $selecthtml .=  "var node;";
  $selecthtml .=  "node = document.getElementById('nkdagilitytimezoneselector');";
  //$selecthtml .=  "alert('moo ' + getSelectedTimezone());";
  $selecthtml .=  "node.value = getSelectedTimezone();";
  $selecthtml .=  "</script>";  

  return $selecthtml;

}

add_action('wp_head', 'nkdagility_timezone_header');
add_action('wp_footer', 'nkdagility_timezone_footer');
add_shortcode('nkdagility-timezone-selector','nkdagilitytimezoneselector');
add_shortcode('nkdagility-time-viewer','nkdagilitytimeviewer');