I am trying to figure out setters in dayjs. To that extent, I tested out the following code:
let orwell = dayjs();
orwell.year(1984);
console.log(orwell.format("YYYY"));
My expectation is that the year 1984 will show up in the console. But that is not the case, instead 2021 shows up.
What am I doing wrong?
Dayjs dates unlike moment dates are immutable. That means that any instance of a dayjs cannot ever ever be changed. The year setter (or any method for that matter) does not modify the instance it is being called on but returns a new dayjs object instead.
Try this:
let now = dayjs();
let orwell = now.year(1984);
console.log(orwell.format("YYYY")); // should print 1984
console.log(now.format("YYYY")); // should print the current year
I don't think I can change the object of 'dayjs'.
However, it is easy to import a value into the 'dayjs()' function as a string.
useEffect(() => {
let orwell = dayjs('1984').format('YYYY-MM-DD HH:mm');
console.log('!!', orwell);
}, []);
Related
I`m currently trying to build up a chatbot/agent with dialogflow and have honestly no knowledge about anything in the programming business/IT stuff. I´m a student who had a guestlecture where we were shown how to create Chatbots haha. But I was interested and sat down and tried to create one for my work. A simple bot that tells the customer about the opening times and gives out some information to save us some phone calls. So far so good. I want to include the function to book a table and my problem is the following:
I´ve read many questions about changing the date and time format to receive a format like "4pm on Thursday" instead of "2020-12-26T16:00:00+01:00".
So as I said I have no clue so far how the change the code to get a different output so my question would be if you could tell me where exactly I have to do that or where I can find a solution for that. Don´t get me wrong I´d love to know how to do it so yeah I´d be so happy if you could save that christmas present :)
Best regards
Mo
So, your question is vague and lacks details.
If you want to convert "2020-12-26T16:00:00+01:00" to "4pm on Thursday" in your local time here are helper functions to achieve that:
function convertParametersDateTime(date, time){
return new Date(Date.parse(date.split('T')[0] + 'T' + time.split('T')[1].split('+')[0]));
}
// A helper function that adds the integer value of 'hoursToAdd' to the Date instance 'dateObj' and return a new Data instance.
function addHours(dateObj, hoursToAdd){
return new Date(new Date(dateObj).setHours(dateObj.getHours() + hoursToAdd));
}
// A helper funciton that converts the Date instance 'dateObj' into a string that represents this time in English.
function getLocaleTimeString(dateObj){
return dateObj.toLocaleTimeString('en-US', {hour: 'numeric', hour12: true});
}
// A helper dunction that converts the Date instance 'dateObj' into a string that represents this date in English
function getLocaleDateString(dateObj){
return dateObj.toLocaleDateString('en-US', {weekday: 'long', month: 'long', day: 'numeric'});
}
Those are the helper functions. You have to call them inside the Fulfillment function for your intent. Here's a very simple example:
function makeAppointment (agent) {
// Use the Dialogflow's date and time parameters to create Javascript Date instances, 'dateTimeStart' and 'dateTimeEnd',
// which are used to specify the appointment's time.
const dateTimeStart = convertParametersDateTime(agent.parameters.date, agent.parameters.time);
const dateTimeEnd = addHours(dateTimeStart, appointmentDuration);
const appointmentTimeString = getLocaleTimeString(dateTimeStart);
const appointmentDateString = getLocaleDateString(dateTimeStart);
agent.add(`Here's the summary of your reservation:\nDate&Time: ${appointmentDateString} at ${appointmentTimeString}`);
}
The codes might include some syntax errors. Those functions give what you are looking for but you would have to adjust them according to your needs.
We are trying in a RESTLet to access the sublist "demandplandetail" from a NetSuite Item Demand Plan. Everything goes fine until a certain point. We are able to load it and process the demandplan for 2020. However, here it gets frustrating.
We know (can see from NetSuite) that there is data also for 2021. However, to access that from SuiteScript seems very difficult.
1st solution) The item demand plan has the field "year". OK, just set that to 2021, save and reload the record. Result: saving ignored, year still is 2020.
2nd solution) Set the year using a Date object as in:
var demandPlan = record.load(...)
var d = new Date();
demandPlan.setValue({
fieldId: 'year',
value: d
});
Gives the following:
:"TypeError: Cannot find function getFullYear in object NaN. (NLRecordScripting.scriptInit$lib#59)","stack":["setDatesForMonthAndYear(NLRecordScripting.scriptInit:108)","anonymous(N/serverRecordService)"
on saving the record. I also get the same using (various) strings adhering to acceptable date formats (as in '1/1/2021'). I have also tried the format package giving me a date string -> the same result.
Also read somewhere that you may need to set the start date (field 'startdate') in the record. Tried several variations but it stubbornly refuses :(.
Wonder if anyone has seen anything similar?
Best Regards,
Toni
Hi Please try the below code also check if you're passing date object to the field not the date string.
function formatDate() {
var dateROBD = format.parse({
value: new Date(),
type: format.Type.DATE
});
// this line optional if you want to try with or else ignore this
dateROBD = convertUTCDateToLocalDate(new Date(dateROBD));
return dateROBD;
}
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
OK, mystery solved. Turned out that this is not supported in SuiteScript 2.0 but you need to use 1.0.
I need help to compare 2 strings that i have and i want to check if one of them has less value than the other so i can throw an alert message.
My code is as followed
if (dateEntered <= date) {
print("DateEntered wrong $dateEntered");
}
The error is that
The operator '<=' isn't defined for the class 'String'.
Try defining the operator '<='
Thank you for your time
In order to compare dates, you need to do something like this,
var df1 = DateFormat('dd-MM-yyyy').parse('22-10-2019');
var df2 = DateFormat('dd-MM-yyyy').parse('25-10-2019');
print(df1.isBefore(df2).toString());
Output: true
Edit : you will have to use install intl package inside pubspec.yaml to use code above,
dependencies:
intl: ^0.16.0
Since you're comparing dates you can use the DateTime class to generate new dates and then use the helper method isBefore to do the comparison. You can also use other helper methods like isAfter and difference
var now = new DateTime.now();
var earlier = now.subtract(const Duration(seconds: 5));
if(earlier.isBefore(now)){
print('Earlier is 5 seconds before now, so earlier.isBefore(now) is true');
}
In node.js:
Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
console.log("====>", new Date(2019, 0, 1))
I would expect "2/11 of 2019", instead I get "2019-01-01T02:00:00.000Z".
Is node.js broken?
You may think that logging a Date calls the Date object's toString function, so you could just override it - but that's not necessarily true. Some implementations will give you output similar to toISOString instead of toString. Nowhere in the ECMAScript spec does it define how console.log should behave. Even in the WhatWG Console Standard, it doesn't describe how to log Date objects - so you're in implementation dependent territory.
So, instead of overriding a function on the Date prototype, you'd have to override the console.log function, check if an argument passed to it is a Date, and if so convert it to a string instead, and then pass it along to the original console.log function. I'll leave that up to you (or someone else) to implement.
Or just remember to call .toString(), as ChuongTran showed in their answer.
I think node.js not broken. But you need to call toString() to get a string in console.log
Date.prototype.toString = function dateToString() {
return `${this.getMonth()}/${this.getDate()} of ${this.getFullYear()}`
};
var date = new Date(2019, 0, 1);
console.log("====>", date.toString());
console.log("====>", date.toDateString());
Output:
====> 0/1 of 2019
====> Tue Jan 01 2019
I have this code, but it fails. Why?
// tomar la fecha
fecha = GLib.Date();
print "cogiendo"
var s = new StringBuilder("Fecha:");
dia:DateDay= fecha.get_day();
s.append_printf ("%u",dia);
print s.str;
fecha_str=s.str;
Glib returns:
g_date_get_day: assertion 'g_date_valid (d)' failed
I would suggest to use the GLib.DateTime class for this purpose.
You didn't write if you want the current date as a locale dependent or independent format.
Locale dependent, using format ():
var dt = new DateTime.now_local ();
stdout.puts (dt.format ("%x"));
Locale independent, using to_string () (beware that this will also include the time):
var dt = new DateTime.now_local ();
stdout.puts (#"$dt");
In a custom format using format ():
var dt = new DateTime.now_local ();
stdout.puts (dt.format ("%d/%m/%Y")); // 29/09/2014
I took the custom format from your own answer, but I wouldn't use it as it's confusing, because usually with / delimited dates have the format "%m/%d/%Y" or "%m/%d/%y".
I would prefer either the locale default format (which is what the user expects) or the ISO 8601 format which you get with to_string () or without the time with format ("%F").
From the documentation:
If the Date-struct is obtained from g_date_new, it will be safe to mutate but invalid and thus not safe for calendrical computations.
Perhaps you want to set_time_t, or set_time_val. If you want today's date, fecha.set_time_t(time_t());
This code goes well!! Searched in gnome's vala samples:
var now = new DateTime.now_local ();
fecha_str = now.get_day_of_month ().to_string()+"/"+now.get_month ().to_string()+"/"+now.get_year ().to_string()