Getting different date pattern when using dojo.formToJson - javascript

I have changed the datePattern of dijit/form/DateTextBox by providing an attribute
<form dojoType="dijit.form.Form" data-dojo-id="calc_form" id="calc_form">
<input type="text" data-dojo-type="dijit/form/DateTextBox" data-dojo-id="CONTRACT_DATE"
id="CONTRACT_DATE" name="CONTRACT_DATE"
constraints="{datePattern:'MM-dd-yyyy', strict:true}" />
</form>
i.e the attribute is constraints="{datePattern:'MM-dd-yyyy', strict:true}" and I got the date pattern shown correctly in the page as '01-28-2016'.
But when I tried to get the JSON of the form containing the dijit/form/DateTextBox using dojo.formToJson("formID"), I am getting a different value then the assigned pattern: '2016-01-28'
Why? Is there any solution for that?

The sole purpose of datePattern is to format the way the user types the date into the DateTextBox.
No matter what format the user types the date in, internally Dojo works in the ISO date format by design. This also makes it easier on you, the programmer.
If you're looking into converting ISO into another proprietary format, there's a module for that.
require(['dojo/date/locale'], function(locale) {
var date = locale.parse('2016-01-28', {
datePattern: 'yyyy-MM-dd',
selector: 'date'
});
var formattedDate = locale.format(date, {
datePattern: 'MM-dd-yyyy',
selector: 'date'
});
console.log(formattedDate);
});

The probleme is in the dojo.formToJson it return the default date format
whatever you specify the format in the dijit/form/DateTextBox input.
So , I suggest to format the date inside the generated jsonForm ,
here is a solution :
First import the required js ,
//AMD loading
require(["dojo/date/locale","dojo/json"],
function(locale,JSON){
......
})
"dojo/date/locale" used here to change date pattern
"dojo/json" used to Parse o json Object or reverse (Object to String)
then declare the formatJsonFormDates function
( params are explained in the code it return a new jsonForm with formatted date)
helps you to convert all date at ones if there is many dates in the Form, by
passing the name attribute of the input date in an Array parameter
//helper function
/**
* The function get generated 'form' from dojo.formToJson(HTML from),
* and replaces all string Date to the desired format
* ("YYYY-MM-dd" to "MM-dd-YYYY" by exemple)
*
* #param string jsonForm Value of generated jsonForm(HTML from)
* #param Object form Value of the Dijit.form.Form
* #param Array dateFieldsNames string array Values of date form fields to be formatted
* #param string datepattern Values of the wanted Dateformat // "mm-dd-YYYY"
*
* #return string jsonFormObject Value of new Returned jsonForm with desired date format
*/
var formatJsonFormDates = function(jsonForm,form,dateFieldsNames,datepattern){
//if no field passed to the function return default
if(!fieldsNames.length && fieldsNames.length < 1 ) return jsonForm;
jsonFormObject = JSON.parse(jsonForm);
for(var i = 0; i<fieldsNames.length ;i++){
//check if field is an instance of Date
if(form.getValues()[fieldsNames[i]] instanceof Date) {
newDate = locale.format(form.getValues()[fieldsNames[i]],{datePattern: datepattern, selector: "date"});
jsonFormObject[fieldsNames[i]] = newDate;
}
}
return JSON.stringify(jsonFormObject);
}
finnaly , after getting your jsonForm apply the function on it :
var formData = dojo.formToJson("yourFormID");
//I recomoand to use dijit/registry instead of dijit
formData = formatJsonFormDates(formData,dijit.byId("yourFormID"),["CONTRACT_DATE"],"MM-dd-yyyy");
.

Related

Can't convert timestamp to date properly in Javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/
Try this: new Date(timestamp.getHighBits() * 1000)

ion-datetime: How to get date value without timestamp?

I'm using ion-datetime in ionic4 using NgModel to bind to a property, however, no matter what options I include in format, I always get the time with the timestamp included. ¿How can I remove timestamp from result so the final value of my property is something like "2019-04-22" instead of "2019-04-22T08:45:41.243-05:00"?
I tried: but, I'm still getting the timestamp
<ion-datetime max="2030" min="2019" [(ngModel)]="mydate" display-format="MMM DD, YYYY"></ion-datetime>
I expect the result to be like: "2019-04-22", but I keep getting: "2019-04-22T08:45:41.243-05:00"
If you want only date then I think split() method might works,beacause value we get from ion-datetime is a string.So we use split method which split string and convert it to an array,and you can get date or time which thing you want with the help of index as follow:
var dateFormat = mydate.split('T')[0];
console.log(dateFormat);
// 2019-04-22
You can format the date with Moment.js.
<ion-datetime displayFormat="MMM DD, YYYY" max="2030" min="2019" [(ngModel)]="mydate" (ionChange)="doSomething(this.mydate)"></ion-datetime>
import * as moment from 'moment';
doSomething(date) {
console.log('date', moment(date).format('YYYY-MM-DD')); // 2019-04-22
}
You can use custom picker options to set custom buttons, it returns an object with all the variables in separate keys, so it makes it easier to edit the way you want it to display
To do so, you would insert this in your ion-datetime
[pickerOptions]="customPickerOptions"
and in your .ts file
this.customPickerOptions = {
buttons: [
{
text: 'Save',
handler: (time) => {
console.log('time', time);
}
},
{
text: 'Cancel',
handler: e => {
modalCtrl.dismiss(e)
}
}
]
}
Hope this helps
<ion-datetime
displayFormat="DD.MM.YYYY"
presentation="date"
[(ngModel)]="date"></ion-datetime>
<div>{{date.split('T')[0]}}</div>
in Ts file
data:any='';
You can use moment.js
in your file.page.html
<ion-datetime [(ngModel)]="mydate" placeholder=""></ion-datetime>
in your file.page.ts
import moment from 'moment';
<!-- to pass data to your API -->
mydate = moment(mydate).format('YYYY-MM-DD');
<!-- to view in console -->
yourFunction(mydate) {
console.log('date', moment(mydate).format('YYYY-MM-DD'));
}
May this answer helps. I understand how frustrating it can be to find the answer we are looking for.
Edit2: toLocaleFormat is not widely accepted. Here is a post on alternatives. You could just split it around the T.
const dateArray = fullDateString.split('T');
if (dateArray.length > 0){
const partYouWant = dateArray[0];
}
Edit: From the Ionic docs
It's also important to note that neither the displayFormat or
pickerFormat can set the datetime value's output, which is the value
that is set by the component's ngModel. The format's are merely for
displaying the value as text and the picker's interface, but the
datetime's value is always persisted as a valid ISO 8601 datetime
string.
Here is a better answer:
const dateObject = new Date(this.mydate);
const dateString = dateObject.toLocaleFormat('%Y-%m-%d');
An input for new Date can be a date string defined as:
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
I'm guessing you are trying to access this.mydate in your code.
You have several options, best represented by this stack overflow post.
this.mydate.toLocaleFormat('%Y-%m-%d');
This function will take a Date object and convert it to the string in the format you requested. All the options you can put in the options are here.
There are also plenty of other options shown in the stack overflow post above.
install date-fns by npm i --save date-fns
import {format} from "date-fns"; in your .ts file
let date_x = "2019-11-30T14:42:30.951+08:00";
format(new Date(date_x), "yyyy-MM-dd");
you should get as result in console => '2019-11-29'
This is the best way to get the exactly time
First Create the $event method like this
changeTime(e) {
this.sentTempTime = "";
let hoursMinutes = e.split(':');
this.sentTime = this.formatTime(hoursMinutes);
}
after that create the formatTime() method like this
formatAMPM(date) {
var hours = date[0].toString().split('T'); //22
var minutes = date[1]; //11
var ampm = hours[1] >= 12 ? 'pm' : 'am'; //22 >=12 yes == pm
hours = hours[1] >= 12 ? hours[1] - 12 : hours[1]; //22 >= 12 ? 22-12=10
var strTime = hours + ':' + minutes + ampm;
return strTime;
}
after that you can able to get the time like this 08:15pm
In Ionic 6 you just need the presentation property.
Set it to date and it will only render the date picker, without the time picker.
<ion-datetime presentation="date"></ion-datetime>
See the presentation property in the docs for more details.

How to change the filtering pattern of the Webix dateFilter?

How to specify the format of the dateFilter in Webix datatable?
I have a grid where dates are formatted to "%d.%m.%Y":
columns:[
{ id:"date", header:[{ content:"dateFilter" }], width:160, format:myFormat }
]
where myFormat is webix.Date.dateToStr("%d.%m.%Y"); The result is dd.mm.yyyy
Here's a snippet with the similar grid: http://webix.com/snippet/1ec86aa8
The point is that the dateFilter still requires the full dates as %m-%d-%Y (mm-dd-yyyy)
So I'm looking for a way to change this predefined pattern. Any suggestion are appreciated.
dateFilter convert user entered date from str to date using webix.i18n.dateFormatDate
By the way, it does more thing. For exemple you can enter "<1996" and so it will not convert using the above method date but extract the year.
Then it convert the guessed date to an interger and perform an interger comparison with data's dates
Sadly "webix.i18n.dateFormatDate" use the webix.i18n.dateFormat which depend the locale to convert string to date. and there is no way to customize the format used by dateFilter.
A solution for you is to create a custom filter which do the same job as dateFilter but using your own date convertion :
Here is a modified webix code of dateFilter :
webix.ui.datafilter.myDateFilter = webix.extend({
format:function(value){
if (value === "") return "";
var date = new Date();
if (value.indexOf("today") != -1){
date = webix.Date.dayStart(date);
} else if (value.indexOf("now") == -1){
var parts = value.match(/[0-9]+/g);
if (!parts||!parts.length) return "";
if (parts.length < 3){
parts.reverse();
date = new Date(parts[0], (parts[1]||1)-1, 1);
} else
// Change here
date = webix.Date.strToDate("%d.%m.%Y")(value.replace(/^[>< =]+/,""));
}
return date.valueOf();
}
}, webix.ui.datafilter.numberFilter);
Updated snippet : http://webix.com/snippet/20c0175a

Formatting date in ExtJs

I am working with ExtJS and want to use Ext.Date.format(value,format). I have date as 2014/03/05. How can I convert this to the date object so that it can be passed as 'value' argument to the format() function?
You can try this :
var dt = new Date('2014/03/05');
And you do this to format your date Ext.Date.format(dt,'d-m-Y'); or whatever format you want. :)
You can parses date:
var dt = Ext.Date.parse("2014/03/05", "Y/m/d");
Then you can format it another format:
var td = Ext.Date.format(dt,'d-m-Y');

Javascript convert dates

I am getting this "20131218" date/time value from an API result.
What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:
echo date("Y-m-d",strtotime('20131218'));
output: 2013-12-18
This is what I tried in javascript:
var myDate = new Date("20131218");
console.log(myDate);
But the output is Date{ Invalid Date } so obviously this is wrong.
My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?
Your help will be greatly appreciated!
Thanks! :)
The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218
Or convert the value you get in your Javascript to similar kind of format.
var dateVal="20131218";
/*
// If it's number ******* //
var numdate=20131218;
var dateVal=numdate.toString();
*/
var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;
var actualDate = new Date(dateString);
alert(actualDate);
JSFIDDLE DEMO
Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:
function formatDateStr(s) {
s = s.match(/\d\d/g);
return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}
alert(formatDateStr('20131218')); // '2013-12-18'
If you wish to convert it to a date object, then:
function parseDateStr(s) {
s = s.match(/\d\d/g);
return new Date(s[0] + s[1], --s[2], s[3]);
}
The reason why it is showing Invalid date is, it wants it to be in format
Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.
1. var myDate = new Date("2013-12-18");
alert(myDate);
2. var myDate = new Date(2013,12,18);
Eventually you can modify your string manipulate it and use it in aforementioned format.

Categories

Resources