Search code examples
c#razormodel-view-controllertwitter-bootstrap-3datetimepicker

How to assign UtcNow to a DateTime picker value property?


I'm using the Bootstrap 3 DateTime picker from here. On load of the Razr form I want to set the default time as the current UtcNow time stamp.

I've tried a number of different DateTime formats in order to set this default. But the control doesn't seem to accept the formats passed in.

Some of the formats tried:

//Format #1
DateTime.UtcNow.ToString("yyyyMMddHHmmtt");

//Format #2
string.Format("{0:g}", DateTime.UtcNow);

I know that the format used by the DateTime picker when selecting a time is as follows, 07/13/2016 2:43 AM, so I think if I can convert the UTC time to this format it will accept the time stamp.

I verified that I can assign this value to a regular input element with the same Razr syntax, so that rules out an issue with the value not being passed over.

Question:

How can you assign UtcNow to a DateTime picker default value property?

Controller: In the controller I pass in the string.Format("{0:g}", DateTime.UtcNow); as a model property.

//Create a dynamic object to store list of different model types.
dynamic dynamicEscalationModel = new ExpandoObject();
dynamicEscalationModel.OutageStartTime = string.Format("{0:g}", DateTime.UtcNow);

View: I then use a @ symbol to assign this value to the DateTime picker:

<!-- Outage Start -->
<div class="form-group">
    <label class="col-md-9 control-label" style="text-align: left;" for="OutageStartDisplay">Outage Start (*UTC)</label>
    <div class="col-md-9">
        <div class='input-group date' id='OutageStartDisplay'>
            <input type='text' class="form-control" id="OutageStartDisplayInput" name="OutageStartDisplayInput" value="@Model.OutageStartTime" />
            <span class="input-group-addon" id="OutageStartDisplayCalendar">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>

For testing I added a second normal input and the model property is bound correctly:

<input type='text' class="form-control" id="" name="" value="@Model.OutageStartTime" />

The DateTimepicker init in my script tag:

//Init the Outage Start date time picker
$(function () {
    $('#OutageStartDisplay').datetimepicker({
    });
});

Solution

  • Since you are getting the UTC now, why not do it from client side directly:

        <script type="text/javascript">
            $(function () {
                var t = new Date(); 
                t.setMinutes(t.getMinutes() + t.getTimezoneOffset());
    
                $('#OutageStartDisplay').datetimepicker({
                    defaultDate: t,
                });
            });
        </script>