How to mock up Date object? - coffeescript

I'm trying to write jasmine test for this method
currentTime: ->
Math.round(new Date().getTime()/1000)
In the test trying this:
#date = new Date()
#date = Date(#date.getTime() + 70)
spyOn(window, "Date").andCallFake ->
#date
expect(#user.currentTime()).toEqual xxx
I tried #date = new Date(#date.getTime() + 70) but I didn't help.
But I got error:
Uncaught TypeError: Object [object Object] has no method 'getTime'
Any idea how to fix it? Thanks

You have to mock the Date constructor so that he returns a mock for getTime that returns always the same int:
spyOn(window, "Date").andReturn {getTime: -> 1000}

The solution was taken from here
#_Date = Date
testContext = #
time = new Date().getTime() + 400
spyOn(window, "Date").andCallFake ->
new testContext._Date(time)

Related

Convert String to Date in Groovy

I want to get the date time add minutes or hours, below code is working for me
def now = new Date();
use(groovy.time.TimeCategory) {
def new_date = now + 10.minutes;
}
Now the issue is the "10.minutes" is a variable come from other place, once I got it, it change to string.
So is there any method i can convert String (10.minutes) to like a object which i can use it to add with a date?
This works for me:
def now = new Date()
use(groovy.time.TimeCategory) {
String t = "10.minutes"
def new_date = now + evaluate(t)
println new_date
}

How can I display current Timezone offset in GMT, in Elm

I'm stuck on getting the current Timezone offset from the Date in Elm.
Date.now
This returns
<Thu Feb 22 2018 20:42:42 GMT+0530 (India Standard Time)> as string
As I have explored in Elm's core lib of date and time, and they don't provide any direct method to fetch the current timezone offset. So what should I do?
import Html as App
import Html exposing (..)
import Date exposing (Date)
import Task
type alias Model =
Maybe Date
type Msg =
SetDate (Maybe Date)
update : Msg -> Model -> (Model, Cmd Msg)
update (SetDate date) _ =
(date, Cmd.none)
view : Model -> Html Msg
view model =
div [] [ text <| dateString model ]
dateString : Model -> String
dateString model =
case model of
Nothing -> "No date here"
Just date ->
(toString <| date)
now : Cmd Msg
now =
Task.perform (Just >> SetDate) Date.now
main : Program Never Model Msg
main =
App.program
{ init = ( Nothing, now )
, view = view
, subscriptions = always Sub.none
, update = update
}
I need this +0530 as in the float 5.5.
Elm's DateTime functions are pretty sparse at the moment, but justinmimbs Date.Extra library is my go to for this type of problem. Check it out here
You can import it as such,
import Date.Extra exposing (offsetFromUtc)
And, then where you had toString <| date change your pipeline to
date
|> offsetFromUtc
|> toString
That'll give you your offset in minutes, if you want the float value, just divide the int by 60. Simple function here to do so:
divBy60 : Int -> Float
divBy60 t =
toFloat t / 60.0
then just change your pipeline again to
date
|> offsetFromUtc
|> divBy60
|> toString

Google script not recognising date

I'm trying to write some code to check values in a spreadsheet column to see if they are valid dates. However, even if I put in a date in a cell with the format set to date, it doesn't seem to recognise it as a date. When I debug the date objects are listed as "new Date" but if I attempt to ask Logger to getDate() I receive the following error :
TypeError: Cannot find function getDate in object Sat Jun 05 2010 01:00:00 GMT+0100 (BST). (line 15, file "myCode")
I can set my objects as dates by calling 'new Date()' which means that they are recognised as dates but this changes all the objects to dates whether they should be or not.
Here is my code:
function onMyPress(){
var sheet = SpreadsheetApp.getActive().getActiveSheet()
var myRange = sheet.getRange(2,2,8,1)
var myValues = myRange.getValues()
for (i=0; i<8; i++){
var testDate = myValues[i]
if (isDate(testDate)) {sheet.getRange(i+2,3,1,1).setValue("Date")
}
else{
sheet.getRange(i+2,3,1,1).setValue("Not Date")
}
Logger.log(testDate.getDate())
}
}
function isDate(testDate) {
if (Object.prototype.toString.call(testDate) !== "[object Date]") {
return false;
}
else {
return true;
}
}
Thanks for looking.
The problem is that getValues() returns a 2D array and you script assigns a "row" (a
JavaScript array) instead of cell value (a JavaScript string, Date, etc.) to testDate on the following line
var testDate = myValues[i]
One alternative is to replace the above code line by by something like the following:
var testDate = myValues[i][0]
assuming that your dates are on the first column.
"Cannot find function getDate in object" means that you are calling getDate() on an object that is NOT a Date object.
I am guessing "testDate" is a String object? If you step through the code, does it go into the "else" clause?
You need to:
Check that your String object contains a correctly formatted date
(which seems to be the case)
Then CONVERT it to a Date object, like this: var realDate = new Date(testDate);
See working example here:
https://jsfiddle.net/uyowax8o/
// Convert to Date object
var realDate = new Date(testDate);
// This now works
alert(realDate.getDate());

Strange issue while summing time interval and date in Swift 3

While trying to sum date and timeinterval i am getting Ambigous use of operator + error. How can it be fixed?
func +(date: Date, timeInterval: Int) -> Date {
return date + TimeInterval(timeInterval)
}
Why are you attempting to define such a + operator? Swift already provides one.
The following works just fine:
let date = Date()
let interval = TimeInterval(45)
let newDate = date + interval
And the code you posted in your question works just fine for me.
func +(date: Date, timeInterval: Int) -> Date {
return date + TimeInterval(timeInterval)
}
let date = Date()
let interval = 45
let anotherDate = date + interval

Groovy : Find the date of the previous Monday

In the following code, i want to find the date of the last Monday.
For that, i have two variable :
startDay = today - 7 days
stopDay = today - 1 day (yesterday)
And i have a function that list all dates between "startDay" and "stopDay", and search in these dates, which one corresponds to Monday.
It works well when i have two dates in the same ten :
startDay = 2014-07-20
stopDay = 2014-07-29
But, when one of both change decade, the code end with an error:
startDay = 2014-07-29
stopDay = 2014-07-30
ERROR:
java.lang.IllegalArgumentException: Incompatible Strings for Range: String#next() will not reach the expected value
CODE:
def searchDay = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}").format("u") == "1" } }
def startDay = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()-7)
def stopDay = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()-1)
def dateOfTheDay = searchDay(startDay, stopDay);
def dateOfTheDayWithoutSquare = dateOfTheDay.join(", ")
return dateOfTheDayWithoutSquare
This will find the previous Monday starting from today
def cal = Calendar.instance
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DAY_OF_WEEK, -1)
}
Date lastMonday = cal.time
// print the date in yyyy-MM-dd format
println lastMonday.format("yyyy-MM-dd")
If you want to find the Monday previous to some other date replace the first line with:
def cal = Calendar.instance
Date someOtherDate = // get a date from somewhere
cal.time = someOtherDate
This should be a touch faster (no loop):
def cal = Calendar.instance
def diff = Calendar.MONDAY - cal.get(Calendar.DAY_OF_WEEK)
cal.add(Calendar.DAY_OF_WEEK, diff)
cal.time.format("yyyy-MM-dd")