Mocking moment format with timezone in jest - javascript

I'm testing a service which formats a date based in a timezone, it's working perfectly, but when I'm running the tests, I'm receiving the error:
moment_timezone_1.default(...).utcOffset(...).format is not a function
I already tried to develop in different approaches which I saw in StackOverflow, but none of them worked, the error message changes (split is not a function, for example).
What can I do to properly mock the moment for my case or use the moment without mocking, but working, obviously?
Here is the function which gives an error:
export function formatTimezone(date, timezone = '+00:00', format = '') {
return moment(date)
.utcOffset(timezone)
.format(format);
}

According to the docs utcOffset(timezone) returns the offset (a number) when no argument is provided. It seems to also do this when null is provided - see below.
console.log(moment().utcOffset(0).format())
console.log(moment().utcOffset(null).format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
You need to validate the timezone input to make sure utcOffset isn't returning a number before calling .format() on it.

Related

Moment object won't increment by days when cloned and used with DateTimePicker

I have the following code:
function localDateHandler(momentObj) {
let start = momentObj.clone();
let update = start.add(10, 'days');
console.log(update); // Does not change, SHOULD be ten days more than momentObj
console.log(momentObj);
}
I am using the following React component to change the date:
<DateTimePicker value={eventDate} onChange={localDateHandler}/>
The info for the component is here: https://material-ui-pickers.dev/
When I change the date the date is not incremented by the number of days listed in the first block of code (I explain more in the comments)
Thank you!
I reproduce and this works with not any problem. What you have seen maybe caused by one of these case:
You might have briefly looked at _i of moment object, this might be the initial object (which could derive from momentObj.clone()), instead, you should look _d instead (moment object internal properties doc)
The most commonly viewed internal property is the _d property that holds the JavaScript Date that Moment wrappers.
You might not have use the right version of peer dependency for moment adapter (installation guide)
Important: For material-ui-pickers v3 use v1.x version of #date-io adapters.
Codesandbox for demonstration, you should open the log to check
JS code works as it should (the comment is clearly false):
function localDateHandler(momentObj) {
let start = momentObj.clone();
let update = start.add(10, 'days');
console.log(update); // Does not change, SHOULD be ten days more than momentObj
console.log(momentObj);
}
localDateHandler(moment());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Yields in my case:
"2020-08-24T22:29:35.347Z"
"2020-08-14T22:29:35.347Z"
I'm guessing something wrong with rendering? Then I suspect you'd have to modify eventDate somewhere in localDateHandler, not some local variable not bound to the widget.

How to convert UTC time to local time in Javascript

My backend is in Django. I used Django's auto_now_add feature on the model to add the current time when that model was created. For example, I am passing this value to the function: 2019-10-08 09:16:20.666754+00:00.
How to convert this in local time in Javascript? I have not coded JS. So the line's a bit blurry for me.
I tried the following method:
function localize_time(date) {
date = new Date(date);
date = date.toString();
}
Then I saw another SO post to add "UTC", that's not working either. when I am calling a said function from Django's template, it's showing following error:
Uncaught SyntaxError: missing ) after argument list
It's on that function.
In Django's template, I am calling the function like this:
<script type="text/javascript">
localize_time({{ user.created_on | safe}});
</script>
If I don't add safe, then the error is:
Uncaught SyntaxError: Unexpected number
Thanks in advance.
I converted the Django's time in milliseconds using datetime.timestamp method and rest of things worked like magic.
you need to add UTC at the end of your date string.
const date = new Date('2019-10-08 09:16:20.666754+00:00 UTC');
alert(date.toString())

show certain date in date picker

I'm using pickmeup datePicker in my Angular project, and it works good and stable but I faced a problem. When I'm trying to set a particular date, picker breaks and/or disappears. I used the method set_date from the documentation but I think I'm missing something.
I use the following code
showDate(timestamp: number) {
const timeString = timestamp.toString();
this.pickerInstance.set_date(new Date(timeString));
}
I have a stackblitz code template here.
So the idea is, I want to have a button when I'm pressing on it, it passes timestamp value to showDate function and after that datePicker shows my date.
I don't want to use jquery here, I believe this could be done without it. But maybe I'm wrong.
Any ideas, comments, help is welcome? thank you.
The constructor of Date needs a number not a a string.
You need to call this.pickerInstance.update() after the update
public showDate(timestamp: number) {
this.pickerInstance.set_date(new Date(timestamp));
this.pickerInstance.update();
}

Kotlin JavaScript Date.now() return type

I was wondering why the Kotlin JavaScript Date class returns a Double for the getTime function. According to the documentation, the getTime function should return the number of milliseconds since 1 January 1970 00:00:00 UTC.
I know that JS doesn't have a 64 bit numeric representation, but since Kotlin emulates Longs I feel like the value returned by Date.now() and Date().getTime() should be a Long. At the very least it would make more sense to return an Int.
Is there any reason that it returns a Double instead of a whole number?
There are two separate reasons for that: consistency and performance.
But before I get into that please note that you can easily get the desired behavior via extensions, e.g.:
inline val Date.time get() = getTime().toLong()
println(Date().time) // 1522757176433
Consistency. As you can see in the Date documentation page, it an external class. Which means it just describes an existing JavaScript API. Is it a good design decision to reuse it as it? Maybe not. But it has a benefit of being familiar to the JS folks. Changing the return type of a single function ruins that and makes the whole API quite inconsistent.
Performance. It is possible hide the original getTime and create a helper function instead. But keep in mind that in order to emulate Long Kotlin creates an object with 2 Number's. Creation, comparison, binary operations, storage - emulated Long's perform a lot worse than native JS Numbers.
Summing up. Changing the return type would make the API inconsistent and inefficient. If you value semantics over performance, just write a few helper functions.
P.S. I think the Date API will be redesigned at some point to make it possible to use it in multiplatform projects. But that's another story.
In kotlin use Date().time .It will return the long Values you will get whole number
val s= Date().time
print(s)
for example
val date = "01-02-2018 07:05:00.999"
val fmt = SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S") //parse date based your format
var myDate: Date? = null
try {
myDate = fmt.parse(date)
} catch (e: ParseException) {
e.printStackTrace()
}
println(myDate)
val timestamp = myDate!!.time //timestamp values in long only not double
println(timestamp)

How to create a datetime object in javascript when using javascript remoteTK/remote toolkit

I am new to salesforce and I know my question sounds silly. But I need someone to tell me the direction I should go.
My question is how can I convert string or object like this
{Start_time__C:"2014-07-24T20:55:00.000+0000"}
and this
{perDiem: true}
into salesforce object. And then I can use create function in remoteTK.
I am currently building custom app on salesforce1. In my visualforce page, I need to create new record, which has datetime, and boolean as its fields.
Thank you in advance!
I don't know much about the remoteTK but before you deep dive into it you might want to look into the "Remote Objects" from Spring'14. This seems to be the new hip / official way of doing remoting (which doesn't mean I'm saying rTK is bad!) and slightly easier to use.
https://salesforce.stackexchange.com/questions/33072/visualforce-remote-objects
https://developer.salesforce.com/blogs/developer-relations/2014/03/spring-14-using-visualforce-remote-objects-with-canjs.html
http://andyinthecloud.com/2014/01/22/spring14-visualforce-remote-objects-introduction/
http://www.salesforce.com/us/developer/docs/pages/Content/pages_remote_objects_example_extended.htm
The main difference between them seems to be that you could use rTK in a non-visualforce page as underneath it just relies on REST callouts. The remote objects use a special VF tag so it's VF-only.
In the end I think it won't matter much which library you'll use. Sample remote object code:
// Create work order line item
var workOrderLineItem = new SObjectModel.WorkOrderLineItem__c();
workOrderLineItem.set('Description__c', 'Answering the question');
workOrderLineItem.set('Hours__c', answer);
workOrderLineItem.set('WorkOrder__c', result[0]);
workOrderLineItem.create(function(error, result, event)
{
// Errors?
if(error!=null)
alert(error);
else
alert('Success');
});
vs. the sample from remoteTK:
var objectType = 'Account';
var fields = {'Name': 'salesforce.com', 'Description':'CRM'};
client.create(objectType , fields,
function(response) {
getAccounts(function() {
$j.mobile.pageLoading(true);
$j.mobile.changePage('#mainpage', "slide", true, true);
});
}, errorCallback);
So a JavaScript object with fields is being created in both cases. For Booleans you should be good sending 'true' or 'false' strings.
For dates you might have to experiment a bit. Generally I've been passing Unix timestamp (miliseconds since Jan 1 1970), this seemed to work OK for me in REST calls or Visualforce Remoting (by which I mean #RemoteAction stuff, yet another tool).
The RemoteTKController.writeFields() seems to be using Date.valueOf(someString) when casting. This means the format should be 'yyyy-MM-dd HH:mm:ss' which is close enough - check if it will work out of the box and remove the timezone part from your string if it causes problems? You could simplify your examples a lot by skipping the remote part and directly check in Developer Console or Execute Anonymous how the parser reacts to different dates you'll feed it.
There's another function that seems to use REST API instead of the controller. This one will just pass the payload to REST API's POST request. Looking at how it's built you should be fine just passing a real JavaScript Date object as value, the JSON.stringify call should figure out how to serialize that. If you really want to craft the string yourself - check the REST API guide. The dates should look like that and all remoteTK'create call does is make a request similar to this one
This is an old thread, but in case it helps someone I was able to get this working. The yyyy-MM-dd HH:mm:ss format was very close. All it needed was a 'T' between the date and time to be acceptable. From there is was just making sure that all components came through as two digits, and converting the date to UTC time. Here's my final Javascript function:
function ConvertDate(dtin){
var d = new Date(dtin);
var convertdate = d.getUTCFullYear() + '-' + ('0' + (d.getUTCMonth()+1)).slice(-2) + '-' + ('0' + d.getUTCDate()).slice(-2) +'T' + ('0' + d.getUTCHours()).slice(-2)+':'+('0' + d.getUTCMinutes()).slice(-2)+':'+d.getUTCSeconds()+'0';
return convertdate;
}
From there I could pass the converted date to the sObject function without error.

Categories