Moment.js: Convert datetime string into UTC - momentjs

I'm trying to use moment.js library to convert a datetime string into a local UTC. How do I do that?
html:
<div style="float:left; margin-right: 5em;">
<label id="startDateTimeLabel">Start DateTime</label>
<div class="input-group input-append date" id="startDateTime" style="width:300px;">
<input type="text" class="form-control">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
<input id="ButtonConnect" class="btn btn-primary" type="button" value="Connect" onclick="ButtonGetSelectedDate();" />
<script>
const startPicker = new tempusDominus.TempusDominus(document.getElementById('startDateTime'));
var tStartDatetime = startPicker.dates.picked;
//the below line seems to be a javascript datetime;
console.log('tStartDatetime : ' + tStartDatetime ); //this is the format: Sat May 15 2021 12:30:00 GMT-0400 (Eastern Daylight Time)
var tStart = moment(tStartDatetime ).valueOf();
console.log('tStart : ' + tStart ); //this prints Nan on the console
</script>

this is what I did and it seems to work ok.
tStart = moment(new Date(tStartDatetime)).valueOf();

Related

KnockoutJS Required (ifonly) not being honored when observable changes

I have 2 fields that I need to required based on another field in my model. The first field is functioning as desired, however the second field (similar logic) doesn't honor the required attribute. I have verified that the onlyif code is firing when the observable is changed. However the form allows submission if the required fields are not filled in.
JS Code
//Works As Expected
self.model.RecentLocations.LastDayOnSite.extend({
required: {
onlyIf: function () {
return ((!self.model.RecentLocations.IsLastDayOnSiteNA()) && (self.model.CaseType() != 'Quarantine'));
}
}
});
//Not Requiring Field as expected.
self.model.ContactTracingStartDate.extend = ko.observable().extend({
required: {
onlyIf: function () {
return (self.model.IsContactTracingRequired() == "Y");
}
}
});
HTML Code
//Works As Expected
<div class="col-md-2 form-group">
<i id="lastDayOnSite-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="hidden: (model.RecentLocations.IsLastDayOnSiteNA() || model.CaseType() === 'Quarantine')"></i>
<label for="lastDayOnSite-datepicker_nfd">Last Day on Site</label>
<input type="text" class="form-control datepicker_nfd" id="lastDayOnSite-datepicker_nfd" data-bind="value: model.RecentLocations.LastDayOnSite, preventFutureDate: model.RecentLocations.LastDayOnSite, disable: model.RecentLocations.IsLastDayOnSiteNA()" data-emessage="Last Day on Site" placeholder="Date">
</div>
//Not Requiring Field as expected.
<div class="col-md-2 form-group">
<i id="contactTracingStartDate-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="visible: (model.IsContactTracingRequired() === 'Y')"></i>
<label for="contactTracingStartDate-datepicker_nfd">Contact Tracing Start Date</label>
<input type="text" class="form-control datepicker_nfd" id="contactTracingStartDate-datepicker_nfd"
data-bind="value: model.ContactTracingStartDate,
preventFutureDate: model.ContactTracingStartDate, enable: (model.IsContactTracingRequired() === 'Y')" data-emessage="Contract Tracing Start Date" placeholder="Date">
</div>
Not Sure what I am missing here but I am fairly new to KnockoutJS but I can't see where the disconnect is. Any Help or suggestions would be appreciated.
The answer is change the line of code
self.model.ContactTracingStartDate.extend = ko.observable().extend({
TO:
self.model.ContactTracingStartDate.extend({
The problem was the observerable was reset by the ko.observable().extend instead of just extending the existing observable.

Bootstrap datetimepicker - set date time server side

I have a couple of bootstrap datetime pickers and am trying to set the textbox and selected date and time from server, using data read from DB. It keeps setting it to today's date at 12:00 AM.
This is my .aspx and .aaspx.cs file content for the above:
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().beginAsyncPostBack();
function EndRequestHandler(sender, args) {
$('#tpStartDate').datetimepicker({
sideBySide: true,
ignoreReadonly:true,
daysOfWeekDisabled:[0,6]
});
$('#tpEndDate').datetimepicker({
sideBySide: true,
ignoreReadonly:true,
daysOfWeekDisabled:[0,6]
});
}
});
<div class="col-sm-3 col-md-3">
<div class="form-group">
<label for="title">Start Date</label>
<div class="input-group date" id="tpStartDate">
<input runat="server" id="tbStartDateTime" type="text" class="form-control" readonly="readonly" style="cursor:pointer" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" style="cursor:pointer"></span>
</span>
</div>
</div>
</div>
.cs:
tbStartDateTime.Value = dtClassList.Rows[0]["StartDateTime"].ToString();
tbEndDateTime.Value = dtClassList.Rows[0]["EndDateTime"].ToString();
when I put a breakpoint above, I see start datetime is "8/23/2017 1:30:00 PM" and end datetime is "8/23/2017 3:00:00 PM", but on the page they are both displayed as "10/17/2017 12:00 AM" (today's date)
For this you must set as option useCurrent: false as by default useCurrent is true.
If you don't set it will always start the picker on the page with the current date and time.
but on the page they are both displayed as "10/17/2017 12:00 AM"
(today's date)
This is an old bug: https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1311
This was solved on latest version I advise you to use V 4.17.47

moment value can not init data-picker module

I use $scope.dt= moment().format("YYYY-MM-DD") to init datapicker module.
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup ng-model="dt" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open2()">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
this is plnkr test code..
why this can not show value on input?
Moment returns the date as a string, rather than a date object, which is what the datepicker requires, so you need to convert it to a date.
Ex:
$scope.today = function() {
$scope.dt = moment().toDate();
};
$scope.today();
You'll then need to format that if you want it to display properly outside of the datepicker, which you can do when you call it in your view:
{{dt | date: "yyyy-MM-dd" }}
Why moment format value can not init module?
the old version support this.

HTTP Status 500 - Expected session attribute 'consent'

this is my html form of consents. after posting the inputs i get error on the browser
<form th:object="${consent}" action="../users/userDetails.html" th:action="#{${#httpServletRequest.servletPath}}" method="post">
<fieldset>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Service Provider</label>
<select id="provider" name="provider" class="form-control" th:onchange="'javascript:showPIIDoc(this.value);'">
<option th:value="0" >Select a Service Provider</option>
<option th:each="provider : ${user.providers}" name="name" th:value="${user.id} +','+ ${provider.id}" th:text="${provider.name}" >[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">PII Document</label>
<select id ="documentdiv" class="form-control">
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Share with</label>
<select class="form-control">
<option th:value="0" >Select a user you want share the document to</option>
<option name="name" th:each="user : ${users}" th:value="${user.id}" th:text="${user.firstName} + ' ' + ${user.lastName}">[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Consent</label>
<div style="clear:both"></div>
<input type="checkbox" name="share" th:value="1" th:text="Share" />
</div>
<div style="clear:both"></div>
<div style="margin-top:10px;margin-left:10px" class="form-actions">
<button class="btn btn-primary" type="submit">Add Consent</button>
</div>
</fieldset>
</form>
this is my controller
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.POST)
public String processNewConsentForm(#PathVariable("userId") int userId, #PathVariable("providerId") int providerId,
#PathVariable("documentId") int documentId, #ModelAttribute("consent") Consent consent, BindingResult result, SessionStatus status) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
System.out.println("daghade");
System.out.println(provider);
Document doc = this.clinicService.findDocumentById(userId);
Consent c =new Consent();
c.setProvider(provider);
c.setDocument(doc);
c.setUser(user);
c.setStatus(c.getStatus());
c.setFriend(c.getFriend());
System.out.println(c);
if (result.hasErrors()) {
return "providers/createOrUpdateConsentForm";
} else {
this.clinicService.saveConsent(c);
status.setComplete();
return "redirect:/users/{userId}";
}
}
I get this error on the browser
HTTP Status 500 - Expected session attribute 'consent'
after submitting the form
This is the code of Controller for GET Method. it used to call the consent form
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.GET)
public String initNewConsentForm(#PathVariable("userId") int userId,#PathVariable("providerId") int providerId,#PathVariable("documentId") int documentId, Model model) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
Document document = this.clinicService.findDocumentById(documentId);
Collection<User> users = this.clinicService.AllUsers();
Consent consent = new Consent();
model.addAttribute("provider",provider);
model.addAttribute("document", document);
model.addAttribute("user", user);
model.addAttribute("users", users);
return "providers/createOrUpdateConsentForm";
}
add model.addAttribute("consent", consent); in your GET method.

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

Resources