Vue js datepicker, getting only formatted date portion - javascript

I have a working instance of Vue Datepicker, which is functional to the point of picking a date and logging it on select within the console.
The problem is that it logs as Fri Oct 18 2019 15:01:00 GMT-0400 but I need to send the formatted date portion of this like 2019-10-18 only.
This is vuejs-datepicker library and I can't seem to get anything to work with this:
customFormatter(date) {
return moment(date).format('MMMM Do YYYY, h:mm:ss a');
}
What exactly am I doing wrong here?
<datepicker :value="date" #selected="CallDateFunction"></datepicker>
date(){
return {
date: '',
...
CallDateFunction(date){
console.log(date);
}

vuejs-datepicker's selected callback is called with either a date object or null.
You can use the following example code to get a string representation of the date only:
CallDateFunction(date){
if (date) {
const dateString = date.toISOString().substring(0, 10);
console.log(dateString);
} else {
console.log('null date');
}
}

You can format your date with Date.prototype.toISOString() method and set it to your data:
callDateFunction(rawDate){
if (rawDate)
this.formattedDate = rawDate.toISOString().split('T')[0]
}
See also: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

The VueDatePicker have a Props to disable TimePicker that is true by default. As :enableTimePicker="false"
Solution:
<Datepicker v-model="date" :enableTimePicker="false"></Datepicker>
Source: https://vue3datepicker.com/api/props/#enabletimepicker

You can use the javascript function
jsref_toisostring
.
Documentation
Its pretty forward:
var d = new Date();
var n = d.toISOString();

Related

Setting Time input format in Frontend

I'm trying to modify the below code in React Typescript. I want to return the input value in time format like - "Thu Jan 01 2022 13:03:00 GMT-0500 (Eastern Standard Time)" any suggestions how to do it?
Full Code: https://codepen.io/dcode-software/pen/jOwVqGO
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
return `${selects.hour.value}:${selects.minute.value} ${selects.meridiem.value}`;
}
function numberToOption(number) {
const padded = number.toString().padStart(2, "0");
return `<option value="${padded}">${padded}</option>`;
}
activate();
You can create a new Date object and set the hours and minutes on it. From there you get convert it to a string. Like this:
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
const d = new Date();
d.setMinutes(selects.minute.value);
// setHours takes in hours in 24hr format
if (selects.meridiem.value === "pm") {
d.setHours(selects.hour.value + 12);
} else {
d.setHours(selects.hour.value);
}
return d.toString();
}
If you can reach a Date object somehow, its toLocaleString() method can do something like that (the actual parameters are described here.
let date = new Date();
console.log(date.toLocaleString("en-US", {
timeZone: "EST",
dateStyle: 'full',
timeStyle: 'full',
hour12: false // this is because you seem to want a 24-hour format
}));
If you need more, moment.js might be a library to check.

Troubleshooting a Date That Won't Parse in Javascript

Getting date properties back from a C# web API that seemed fine but ran into issues when plugging it into DevExtreme DateBox. It was throwing an error of 'getFullYear is not a function' so I checked the dates against this function I found here -
let r: any = http.post('/get', { Param1: 2, Param2: 1 });
console.log(r.StartDate);
console.log(this.isValidDate(r.StartDate));
r.StartDate = new Date(r.StartDate);
r.EndDate = moment(r.EndDate);
console.log('Start Date', this.isValidDate(r.StartDate));
console.log('End Date', this.isValidDate(r.EndDate));
isValidDate(d: any): void {
if (Object.prototype.toString.call(d) === "[object Date]") {
console.log('it is a date');
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
console.log('date object is not valid');
} else {
console.log('date object is valid');
}
} else {
console.log('not a date object');
}
}
StartDate: "/Date(1657512000000)/"
not a date object
undefined
it is a date
date object is not valid
Start Date undefined
not a date object
End Date undefined
Not sure why this hasn't come up before with this API but didn't want to look to DevExpress given that I can't produce a valid date.
I'm providing this answer to demonstrate one way to parse out the timestamp in the string you have of the following format, inferred by console.log(r.StartDate); ... /Date(TS)/:
// Provided the date has the following structure in a string
var anyStartDate = "/Date(1657512000000)/";
// Prepare to parse it out by getting the positions of the parentheses
var openParens = anyStartDate.indexOf("(");
var closeParens = anyStartDate.indexOf(")");
// Parse out the timestamp
var timeStampStr = anyStartDate.substring(openParens + 1, closeParens);
console.log( timeStampStr ); // 1657512000000
// Convert timestamp to an int. You can do this when you create the obj, but I am separating it here for explanation purposes.
var timeStampInt = parseInt( timeStampStr );
// Now create a date object
var dateObj = new Date( timeStampInt );
console.log( dateObj );
// (on the machine I'm on):
// Outputs: Mon Jul 11 2022 00:00:00 GMT-0400 (Eastern Daylight Time)
// Or outputs: 2022-07-11T04:00:00.000Z
Now I don't know which library(ies) you are using to handle dates so I just went with the native Date object. You can use this SOLUTION however on further insights to apply it to your code.
The point is once the timestamp is extracted, it can be then used to create a Date object, and thus utilize all the methods that are inherent to that class.
In terms of the "timezone", to get it to UTC, it's already in UTC but javascript formats it to your computer's locale. Internally it's still UTC. There's a way to display it as strictly UTC which is in the docs.
`

React native moment formatted date in invalid

I have the following code in my RN application.
getFormattedDate = (date) => {
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
return { date: formattedDate };
}
When I run this on the emulator, the formatted date is displayed properly. But when I run this on device, it says, invalid date. What am I doing wrong here?
From your comments, I assume that the date parameter is a string. If you want to create a new moment from a string, you have to pass the date format. The newly created moment can then be formatted with .format to get a string again.
Change:
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
To:
const formattedDate = moment(date,"MMM, DD YYYY").format("MMMM, DD YYYY");
Here you can find more details about the string format.
npm install date-fns --save
import { format } from 'date-fns'
format(new Date(), 'MMMM, DD YYYY')
Check this document
Moment is 150x slower than new Date . Please try it like this if you want to use this code working.
getFormattedDate = async (date) => {
const formattedDate = await moment(new Date(date)).format('MMMM,DD YYYY');
return { date: formattedDate };
}
you can read it here for more details
https://github.com/moment/moment/issues/731
I would suggest avoid using moment because of the performance.
Use new Date () and then fetch the day , month and year and change into suitable format by joining the strings as you want. Use only Date library.

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.

Property date to String for parsing

I'm trying to insert creation date into table view in specific format.
Now it's like DD/MM/YYYY HH:MM:ss and I want it like DD/MM/YYYY.
YAHOO.Bubbling.fire("registerRenderer", {
propertyName: "test:date",
renderer: function functionPrice(record, label){
var jsNode = record.jsNode,
properties = jsNode.properties;
var rawDate = properties['test:date'];
var date= rawDate().toString().substring(0, 11);
return '<div id="attachments">' + date + '</div>';
}
});
In this case, column contains [Object obj.
I also tried convert it to toISOString but it returns Invalid Date.
Column is set like d:date but output is d:datetime and I don't know why.
Thank you.
If your date format is fixed, this is a safe way to create a Date instance:
var value = "31/12/2017 00:00:00";
var dd = value.substring(0,2);
var mm = value.substring(3,5);
var yyyy = value.substring(6,10);
var d = new Date(yyyy, mm - 1, dd); // Sun Dec 31 2017 00:00:00 GMT+0800 (+08)
To change dates the dates displayed in the date picker control, but this file may not exist in your environment. See if the following file exists:
<alfresco home>\tomcat\shared\classes\alfresco\web-extension\site-webscripts\org\alfresco\components\form\form.get_en.properties
If it doesn’t exist, copy it from here (create the form folder if necessary):
<alfresco home>\tomcat\webapps\share\WEB-INF\classes\alfresco\site-webscripts\org\alfresco\components\form\form.get_en.properties
Open the form.get_en.properties file for editing. Search for “form-control.date-picker” to find the proper properties to change (we found four values on a recent installation).
Restart Alfresco to make the changes take effect.

Categories

Resources