I need to user a date component in Angularjs.
The users asked me allow them to enter the date manually (not with a datepicker) and to put a mask on the input : (__/ __ / __).
Also, important, the date has to have this format : dd/mm/yy.
I have searched on internet but couldn't find such a component.
Does anyone know if it exists?
Thanks in advance.
This blog entry could help
ngModel.$parsers.push(function(data) {
// convert data from view format to model format
var splitted = data.split('.');
var convertedDate = splitted[1] + "/" + splitted[0] + "/" + splitted[2];
return new Date(Date.parse(convertedDate)); // converted
});
Related
I am trying to validate a user input date range. We can accept ISO8601 formatted dates and Date Math Expressions since I am passing it into elasticsearch.
Due to the way the code is, they enter it via an input box so I have to validate the text manually and force them into correct input (unable to transform to proper format).
Sample valid user inputs:
[2021 to 2022]
[2020-12-25T14:48Z to now]
[now-5y to now+1w]
[2020-12-25+1M to now-1m]
Sample invalid user inputs:
[2020-12-25tt4:48Z to now]
[NOW-5y to now+1w]
[now-5y too now+1w]
[2020-12-25+1M To now-1h/d]
So far I [think] I have found a way to confirm the valid ISO8601 and range delimiter but I am having trouble with the regex for the + - / options. This is a snippet of my code so far:
const ALLOWED_NOW_CONSTANTS = /\bnow([+-/][1-9][yMwdhHms])?/; // ISSUE WITH DATE MATHS HERE
const ISO_8601 = /^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/; // ISSUE ADDING DATE MATHS TO THIS ALSO
const validateDateExpression = (dateStr) => {
return ALLOWED_NOW_CONSTANTS.test(dateStr) || ISO_8601.test(dateStr);
}
const str = userInput.trim();
if (str.startsWith('[') && str.endsWith(']')) {
const dateExpression = trim(str, '[]').split(/(\bto\b)/i);
if (dateExpression.length !== 3) {
return '[startTime to endTime]'
}
if ( !validateDateExpression(dateExpression[0].trim()) ) {
return `${dateExpression[0]} is not a valid format`;
}
if ( !validateDateExpression(dateExpression[2].trim()) ) {
return `${dateExpression[2]} is not a valid format`;
}
return ''
}
So my issue with my regex is for the optional "rounded" date maths as well as the date maths for ISO8601. I want to be able to put in the valid date maths but the : now, now/d, now-3M/y, now-1h/d, 2017-03-22+1y, 2020-12-25T14:48:10.78Z+5w/M, 2020-12-25T14:48:10.78Z/M, etc. are cases where I can't seem to get a regex working for this.
This is because of the optional cases where if it is / then it has to be the yMwdhHms that follows instead of a digit. I can't figure out a regex to get this working (now+8h/d or now/y) .
This is also an issue for my ISO8601 date since they can add the date maths at the end and the ISO8601 date is so flexible.
Any help with this is appreciated.
If anything needs clarification on my end or if there's better solutions to this within my current restrictions let me know.
I am currently writing a custom function in Google App Scripts. Right now I am struggling. I defined an argument to take input from a date cell and change the format.
e.g 9/16/2010 to 09.16.2010 where a given column has the former date and the function outputs the latter.
The output is a string, but I can't seem to find any information on this specific text editing feature of javascript.
It's also worth mentioning that the date in a given column is based on a form output, I am not calling a specific short date in the code, so rather this is more string manipulation than date formatting
Any help is appreciated.
/**
*Generates a Trip Key
*
*#param DateColumn Date
*#param SchoolColumn School name
*#param LocationColumn Location
*#customfunction
*/
function GENERATEKEY(DateColumn) {
var Date = DateColumn
const dateStr = Date;
const dateArr = dateStr.split('/');
dateArr[0] = ('0' + dateArr[0]).slice(-2);
dateArr[1] = ('0' + dateArr[1]).slice(-2);
const DateEdited = dateArr.join('.');
return neWDateStr; //gives 00.00.0000
//var Key = Date SchoolColumn "#" LocationColumn
}
Date is a built-in object. It should not be used as a variable name.
While const is allowed in Google Apps Script, it's not fully supported (it doesn't work as the ECMAScript states). IMHO it's better to use var to avoid "confusions".
In Google Sheets, based in the spreadsheet settings, change values entered in supported date-time format into serial numbers and use a number format to display it as date, time, date-time or duration. When a serial number displayed as date, date-time, time or duration is passed to a custom function, Google Apps Script convert it to a Date object.
To return a date formatted use Utilities.formatDate(...) Details in https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate,-timezone,-format
Related
How to format the date in this Google Apps Script
You could simply use inbuilt TEXT function:
=TEXT(A2,"mm.dd.yyyy")
The reason your current script(as provided in one of the previous answers) doesn't work is because the argument DateColumn is not of type String. You can convert the date object to a specific string and format it accordingly or use inbuilt Utilities library.
function DOWHATTEXTDOES(dateColumn) {
return Utilities.formatDate(dateColumn, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy.MM.dd")
}
Essential Reading:
Custom function Data type
Date
You can do something like this
"02/05/2009".split('/').join('.');
Get and Set the numberFormat for the active range
Sheet.getRange().setNumberFormat("mm.dd.yyyy");
Here's a dialog and function that I use sometimes for playing around with different formats. I find it a lot easier and quicker that using the spreadsheet functions.
The top function is a dialog that reads and displays the current format for the active range and has a textbox and button for each cell in the in the active range that allows you to set the number format and see the change immediately.
function getandSetActiveRangeFormats() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getActiveRange();
var fA=rg.getNumberFormats();
var html='<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>A1 Notation</th><th>Number Format</th><th>Enter Format</th><th>Set Format</th></tr>';
var item=1;
var row=rg.getRow();
var col=rg.getColumn();
fA.forEach(function(r,i){
r.forEach(function(c,j){
var txt=Utilities.formatString('<input type="text" id="RC-%s-%s" />',row+i,col+j);
var btn=Utilities.formatString('<input type="button" value="Set Form" onClick="setFormat(%s,%s);" />',row+i,col+j);
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',item++,sh.getRange(row + i,col + j).getA1Notation(),fA[i][j],txt,btn);
});
});
html+='</table><input type="button" value="Exit" onClick="google.script.host.close();" />';
html+='<script>function setFormat(row,col){var f=document.getElementById("RC-"+row+"-"+col).value;google.script.run.setFormat(row,col,f);}</script>';
var ui=HtmlService.createHtmlOutput(Utilities.formatString(html));
SpreadsheetApp.getUi().showModelessDialog(ui, "Display Cell Formats")
}
function setFormat(row,col,format) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.getRange(row,col).setNumberFormat(format);
}
Animation:
Am using moment JS to get the current time. Based on that time I need execute search operation in my elastic search database.
My database entry is like this way :
"message_date": "2014-03-20T09:17:40.482Z"
Moment code to get current time is like this way :
var m = moment();
var testResult = m.toJSON();
// It outputs : 2014-03-20T09:17:40.482Z
My problem is I don't want to include that seconds filed in my database query. I want to search only up to minute field i.e 2014-03-20T09:17. I can split the moment date to get the expected format. But i know its not the way to do that. Please help me to get the expected time format in moment JS way. Thanks
Try:
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
If you want to get the time in a particular timezone:
var m = moment().zone("+05:30");
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
I have to display datetime value on my real time page and i have done following jquery function for that.
function DisplayTimer() {
var x = new Date();
$('#<%=lblTimer.ClientID %>').html(x.toString());
setTimeout('DisplayTimer()', 5000);
}
now i have timezonid value in my session object how can i convert above date value to custom timezone using timezonid session value and also want set datetime format as per culture of user's browser through this jquery function. I have solution in server side code so using [webmethod] i can do that it will make separate request for that every 5 second so i would like to do that without server side interaction. please help me if anyone done this type of logic.
Thanks in adavance.
Change your code with:
var ClientDatetime = x.getMonth() + "/" + x.getDate() + "/" + x.getYear() + " "
+ x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();
take one hidden variable hdnClientDateTime with runate = server and set value as following
hdnClientDateTime.value = ClientDatetime;
Now, Pass hdnClientDateTime.value variable in your server side Datetime format function and assign the value into label like this:
$('#<%=lblTimer.ClientID %>').html(Result);
i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5