0

Мне нужна помощь в моем случае. Я новичок в JS. Я получаю значение (10/19/2016) с текущей страницы и пытаюсь создать объект Date. Но если дата (19/10/2016), она дает мне страницу NaN. Мне нужно что-то вроде этого формата (MyVar, «dd/mm/yy») в любое время, когда была переменная. Как это можно сделать, я действительно застрял на этом.Как форматировать строковую переменную на сегодняшний день в определенном формате?

<link href="{!$Resource.fullCalendarCSS}" rel="stylesheet" /> 
<link href="{!$Resource.fullCalendarPrintCSS}" rel="stylesheet" media="print" /> 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> 
<script src="//code.jquery.com/jquery-1.8.3.js"></script> 
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 

<script src="{!$Resource.JqueryDateFormatJS}"></script> 
<script src="{!$Resource.JqueryDateFormatMinJS}"></script> 
<script src="{!$Resource.DateFormatJS}"></script> 
<script src="{!$Resource.DateFormatMinJS}"></script> 
<script src="{!$Resource.fullCalendarMinJS}"></script> 

<script type='text/javascript'> 

    $.noConflict(); 
    jQuery(document).ready(function() { 
     tempValue = '{!$CurrentPage.parameters.startDate}'; 



     newDate1 = $.datepicker.formatDate("mm/dd/yy", new Date(tempValue)); 
     console.log(newDate1); 
     newDate = new Date(newDate1); 
     console.log(newDate); 



     d = newDate.getDate(); 
     m = newDate.getMonth(); 
     y = newDate.getFullYear();   

    //We need to wrap everything in a doc.ready function so that the code fires after the DOM is loaded 
    //Call the fullCallendar method. You can replace the '#calendar' with the ID of the dom element where you want the calendar to go. 
     jQuery('#calendar').fullCalendar({ 
      year: y, 
      month: m, 
      date: d,             
      defaultView: 'agendaDay', 
      slotMinutes: 15, 
      header: { 
       left: 'prev,next today', 
       center: 'title', 
       right: 'month,agendaWeek,agendaDay' 
      }, 
      editable: false, 
      events: 
      [ 
       //At run time, this APEX Repeat will reneder the array elements for the events array 
       <apex:repeat value="{!events}" var="e"> 
        { 
         title: "{!e.title}", 
         start: '{!e.startString}', 
         end: '{!e.endString}', 
         url: '{!e.url}', 
         allDay: {!e.allDay}, 
         className: '{!e.className}', 
        }, 
       </apex:repeat> 
      ] 
     });   
    });  
</script> 

Я использую плагин fullCalendar и DateFormat.

если моя переменная tempValue в формате «мм/дд/гг» я могу определить объект даты, как:

date = new Date(tempVal) ----> Thu Oct 20 2016 00:00:00 GMT+0300 (Russia TZ 2 Standard Time) 

и если переменная уу будет в формате «дд/мм/гггг» это дает мне ошибку «Недействительная дата».

Мне нужно получить tempValue только в формате «мм/дд/гг», даже если он входит в формат «dd/mm/yy».

+0

Возможный дубликат строки [Parse DateTime в JavaScript] (http://stackoverflow.com/questions/1576753/parse-datetime-string-in-javascript) –

+0

Детали даты потребности OP, расщепленные в любом случае, для FullCallendar. –

ответ

0

Javascript Date() ожидает a couple date string formats ...
Но не dd/mm/yyyy.

Вы заметили это.

Итак, поскольку у вас уже есть правильная дата с даты выбора, почему бы не просто .split это, чтобы найти детали?

Если вы хотите выполнить расчет по датам, например, найти разницу между двумя датами, используйте эти разделенные части, чтобы передать правильный формат Date().

// Commented out because we don't have this value here in this snippet. 
 
//tempValue = '{!$CurrentPage.parameters.startDate}'; 
 

 
// I used this date value instead... 
 
tempValue = "24/09/2016"; 
 

 
console.log(tempValue); 
 

 
//newDate1 = $.datepicker.formatDate("mm/dd/yy", new Date(tempValue)); 
 
//console.log(newDate1); 
 
//newDate = new Date(newDate1); 
 

 
// Get the splitted values 
 
var dateTemp = tempValue.split("/"); 
 

 
d = dateTemp[0]; 
 
m = dateTemp[1]; 
 
y = dateTemp[2]; 
 

 
console.log("d: " + d); 
 
console.log("m: " + m); 
 
console.log("y: " + y); 
 

 
// To perform calculations, you'll need this. 
 
calcDate1 = new Date(m + "/" + d + "/" + y); 
 
console.log(calcDate1.toString());
Just run the snippet and check the console...<br> 
 
;)

+0

Вы также можете использовать эту очень легкую и популярную библиотеку http://momentjs.com/ – gsalisi

+0

@Louys Спасибо за ответ! – Viktor

+0

@Louys, он не разрешил мою проблему (переменная tempValue может быть «24/10/2016» или «10/24/2016», поэтому, если ad var будет 24, новая дата даст мне ошибку «Недействительный день ". Мне нужно отформатировать любой формат даты в единственном формате« мм/дд/гг ». Как я могу это сделать? – Viktor

0

Итак, наконец я нашел решение ... Точная проблема была в Пользовательской местности, поэтому пользователю (состояний Inited) Язык английский есть «M/d/yyyy ', поэтому нам нужно написать код для создания объекта Date для каждого формата даты Locale.

И наконец:

<script type='text/javascript'> 

    $.noConflict(); 
    jQuery(document).ready(function() { 

     tempValue = '{!$CurrentPage.parameters.startDate}'; 

     var userLang = UserContext.dateFormat; 
     var dateTemp = tempValue.split("/"); 

     d1 = dateTemp[0]; 
     m1 = dateTemp[1]; 
     y1 = dateTemp[2]; 

     y=''; 
     d=''; 
     m='';  

     console.log(userLang);  

     if (userLang === "M/d/yyyy") {       

      newDate = new Date(d1 + "/" + m1 + "/" + y1); 
      d = newDate.getDate(); 
      m = newDate.getMonth(); 
      y = newDate.getFullYear();                        
     }; 

     if (userLang === "dd/MM/yyyy") {       

      newDate = new Date(m1 + "/" + d1 + "/" + y1); 
      d = newDate.getDate(); 
      m = newDate.getMonth(); 
      y = newDate.getFullYear();                        
     };    


    //We need to wrap everything in a doc.ready function so that the code fires after the DOM is loaded 
    //Call the fullCallendar method. You can replace the '#calendar' with the ID of the dom element where you want the calendar to go. 
     jQuery('#calendar').fullCalendar({ 
      year: y, 
      month: m, 
      date: d,             
      defaultView: 'agendaDay', 
      slotMinutes: 15, 
      header: { 
       left: 'prev,next today', 
       center: 'title', 
       right: 'month,agendaWeek,agendaDay' 
      }, 
      editable: false, 
      events: 
      [ 
       //At run time, this APEX Repeat will reneder the array elements for the events array 
       <apex:repeat value="{!events}" var="e"> 
        { 
         title: "{!e.title}", 
         start: '{!e.startString}', 
         end: '{!e.endString}', 
         url: '{!e.url}', 
         allDay: {!e.allDay}, 
         className: '{!e.className}', 
        }, 
       </apex:repeat> 
      ] 
     });   
    });  
</script> 

Я думаю, что это не самое лучшее решение, но если у вас есть идея для этого, пожалуйста, скажите мне.

Спасибо!

 Смежные вопросы

  • Нет связанных вопросов^_^