简体   繁体   中英

How to format string variable to date with specific format?

I need help with my case. I'm new to JS. I get the value (10/19/2016) from current page and try to create the Date object. But if the date is (19/10/2016) it gives me an NaN page. I need something like that format(MyVar, "dd/mm/yy") at anytime the variable was. How can it be done, i'm really stuck on this.

<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>

I'm using fullCalendar and DateFormat plugin.

if my variable tempValue in the format "mm/dd/yy" i can define the date object like:

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

and if vy variable will be in the format "dd/mm/yy" it gives me the th error "Invalid date".

I need to get tempValue only in the format "mm/dd/yy" even if it comes in the format "dd/mm/yy".

Javascript Date() expects a couple date string formats ...
But not dd/mm/yyyy.

You noticed that.

So, since you already have a correct date from date picker, why not simply .split it to retreive parts?

If you want to perform calculation on dates, like finding the difference between two dates, then use these splitted parts to pass a correct format to 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> ;) 

So finally i have found the solution... The exact problem was in the User locale, so the user with locale English (Inited states) have a 'M/d/yyyy' date format, so we need to write the code to create the Date object for every Locale date format.

And finally:

<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>

I think this is not the best solution, but if you have some idea for that, please tell me.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM