简体   繁体   English

如何将字符串变量格式化为具有特定格式的日期?

[英]How to format string variable to date with specific format?

I need help with my case. 我的案子需要帮助。 I'm new to JS. 我是JS的新手。 I get the value (10/19/2016) from current page and try to create the Date object. 我从当前页面获取值(10/19/2016)并尝试创建Date对象。 But if the date is (19/10/2016) it gives me an NaN page. 但是,如果日期为(19/10/2016),则会显示NaN页面。 I need something like that format(MyVar, "dd/mm/yy") at anytime the variable was. 我随时都需要这样的格式(MyVar,“ dd / mm / yy”)。 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. 我正在使用fullCalendar和DateFormat插件。

if my variable tempValue in the format "mm/dd/yy" i can define the date object like: 如果我的变量tempValue的格式为“ mm / dd / yy”,则可以定义日期对象,例如:

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". 并且如果vy变量的格式为“ dd / mm / yy”,则会显示错误消息“无效日期”。

I need to get tempValue only in the format "mm/dd/yy" even if it comes in the format "dd/mm/yy". 我只需要以“ mm / dd / yy”格式获取tempValue,即使它以“ dd / mm / yy”格式获取也是如此。

Javascript Date() expects a couple date string formats ... Javascript Date()需要几种日期字符串格式 ...
But not dd/mm/yyyy. 但不是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? 因此,既然您已经从日期选择器中获得了正确的日期,为什么不简单地将其.split为智能零件呢?

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() . 如果要对日期执行计算,例如查找两个日期之间的差,请使用这些拆分的部分将正确的格式传递给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. 所以最后我找到了解决方法...确切的问题出在用户区域设置中,因此具有区域设置英语(初始化状态)的用户具有'M / d / yyyy'日期格式,因此我们需要编写代码来创建每个语言环境日期格式的Date对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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