Unit test a date function - testing

I need to create a unit test for the following function:
export default date => {
const dateInMs = new Date(date).getTime(); // UTC date
const clientDate = new Date();
// timezone offset is in minutes therefore it is being converted to milliseconds
const offset = clientDate.getTimezoneOffset() * 60 * 1000;
return new Date(dateInMs - offset).toISOString();
};
I know I should pass the test a date in the following format
2017-07-01T00:00:00+00:00
Can someone provide some guidance as to how to write a simple test with this information.

Related

Format date with moment vuejs

I hope you can help me, I need to show this format "2021-01-02" (YYY-MM-DD). but only show me 1 digit in month and day.
I have this in my app.js
var moment = require('moment');
getNow: function() {
const today = new Date();
const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
const date2 = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+(today.getDate()-1);
const dateTime = date;
const dateTime2 = date2;
this.hoy = dateTime;
this.ayer = dateTime2;
And I have this in my blade
hoy #{{hoy}} - ayer #{{ayer}}
show me this in my output:
hoy 2021-1-2 - ayer 2021-1-1
but I need to the format be "2021-01-02" because I need 2 digits for compare months and days
PD: Sorry for my english.
Since you are using moment you can try:
const today = new Date();
this.hoy = moment(today).format('YYYY-M-D')

Best way to get current web visitor timezone in asp.net core Razor Pages [duplicate]

I am building an application in MVC3 and when a user comes into my site I want to know that user's timezone. I want to know how to do this in c# not in javaScript?
As has been mentioned, you need your client to tell your ASP.Net server details about which timezone they're in.
Here's an example.
I have an Angular controller, which loads a list of records from my SQL Server database in JSON format. The problem is, the DateTime values in these records are in the UTC timezone, and I want to show the user the date/times in their local timezone.
I determine the user's timezone (in minutes) using the JavaScript "getTimezoneOffset()" function, then append this value to the URL of the JSON service I'm trying to call:
$scope.loadSomeDatabaseRecords = function () {
var d = new Date()
var timezoneOffset = d.getTimezoneOffset();
return $http({
url: '/JSON/LoadSomeJSONRecords.aspx?timezoneOffset=' + timezoneOffset,
method: 'GET',
async: true,
cache: false,
headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }
}).success(function (data) {
$scope.listScheduleLog = data.Results;
});
}
In my ASP.Net code, I extract the timezoneOffset parameter...
int timezoneOffset = 0;
string timezoneStr = Request["timezoneOffset"];
if (!string.IsNullOrEmpty(timezoneStr))
int.TryParse(timezoneStr, out timezoneOffset);
LoadDatabaseRecords(timezoneOffset);
... and pass it to my function which loads the records from the database.
It's a bit messy as I want to call my C# FromUTCData function on each record from the database, but LINQ to SQL can't combine raw SQL with C# functions.
The solution is to read in the records first, then iterate through them, applying the timezone offset to the DateTime fields in each record.
public var LoadDatabaseRecords(int timezoneOffset)
{
MyDatabaseDataContext dc = new MyDatabaseDataContext();
List<MyDatabaseRecords> ListOfRecords = dc.MyDatabaseRecords.ToList();
var results = (from OneRecord in ListOfRecords
select new
{
ID = OneRecord.Log_ID,
Message = OneRecord.Log_Message,
StartTime = FromUTCData(OneRecord.Log_Start_Time, timezoneOffset),
EndTime = FromUTCData(OneRecord.Log_End_Time, timezoneOffset)
}).ToList();
return results;
}
public static DateTime? FromUTCData(DateTime? dt, int timezoneOffset)
{
// Convert a DateTime (which might be null) from UTC timezone
// into the user's timezone.
if (dt == null)
return null;
DateTime newDate = dt.Value - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
return newDate;
}
It works nicely though, and this code is really useful when writing a web service to display date/times to users in different parts of the world.
Right now, I'm writing this article at 11am Zurich time, but if you were reading it in Los Angeles, you'd see that I edited it at 2am (your local time). Using code like this, you can get your webpages to show date times that make sense to international users of your website.
Phew.
Hope this helps.
This isn't possible server side unless you assume it via the users ip address or get the user to set it in some form of a profile. You could get the clients time via javascript.
See here for the javacript solution: Getting the client's timezone in JavaScript
You will need to use both client-side and server-side technologies.
On the client side:
(pick one)
This works in most modern browsers:
Intl.DateTimeFormat().resolvedOptions().timeZone
There is also jsTimeZoneDetect's jstz.determine(), or Moment-Timezone's moment.tz.guess() function for older browsers, thought these libraries are generally only used in older applications.
The result from either will be an IANA time zone identifier, such as America/New_York. Send that result to the server by any means you like.
On the server side:
(pick one)
Using TimeZoneInfo (on. NET 6+ on any OS, or older on non-Windows systems only):
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
Using TimeZoneConverter (on any OS):
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");
Using NodaTime (on any OS):
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/New_York"];
I got the same issue , Unfortunately there is no way for the server to know the client timezone .
If you want you can send client timezone as header while making ajax call .
In-case if you want more info on adding the header this post may help how to add header to request : How can I add a custom HTTP header to ajax request with js or jQuery?
new Date().getTimezoneOffset();//gets the timezone offset
If you don't want to add header every time , you can think of setting a cookie since cookie is sent with all httpRequest you can process the cookie to get client timezone on server side . But i don't prefer adding cookies , for the same reason they sent with all http requests.
Thanks.
For Dot Net version 3.5 and higher you can use :
TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
but for Dot Net lower than version 3.5 you can handle it manually via this way :
first, get Offset from the client and store it in the cookie
function setTimezoneCookie(){
var timezone_cookie = "timezoneoffset";
// if the timezone cookie does not exist create one.
if (!$.cookie(timezone_cookie)) {
// check if the browser supports cookie
var test_cookie = 'test cookie';
$.cookie(test_cookie, true);
// browser supports cookie
if ($.cookie(test_cookie)) {
// delete the test cookie
$.cookie(test_cookie, null);
// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
// re-load the page
location.reload();
}
}
// if the current timezone and the one stored in cookie are different
// then store the new timezone in the cookie and refresh the page.
else {
var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = new Date().getTimezoneOffset();
// user may have changed the timezone
if (storedOffset !== currentOffset) {
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload();
}
}
}
after that you can use a cookie in backend code like that :
public static string ToClientTime(this DateTime dt)
{
// read the value from session
var timeOffSet = HttpContext.Current.Session["timezoneoffset"];
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString();
}
// if there is no offset in session return the datetime in server timezone
return dt.ToLocalTime().ToString();
}
I know the user asked about a non-javascript solution, but I wanted to post a javascript solution that I came up with. I found some js libraries (jsTimezoneDetect, momentjs), but their output was an IANA code, which didn't seem to help me with getting a TimeZoneInfo object in C#. I borrowed ideas from jsTimezoneDetect. In javascript, I get the BaseUtcOffset and the first day of DST and send to server. The server then converts this to a TimeZoneInfo object.
Right now I don't care if the client Time Zone is chosen as "Pacific Time (US)" or "Baja California" for example, as either will create the correct time conversions (I think). If I find multiple matches, I currently just pick the first found TimeZoneInfo match.
I can then convert my UTC dates from the database to local time:
DateTime clientDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo);
Javascript
// Time zone. Sets two form values:
// tzBaseUtcOffset: minutes from UTC (non-DST)
// tzDstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
var form = document.forms[0];
var janOffset = -new Date(2016, 0, 1).getTimezoneOffset(); // Jan
var julOffset = -new Date(2016, 6, 1).getTimezoneOffset(); // Jul
var baseUtcOffset = Math.min(janOffset, julOffset); // non DST offset (winter offset)
form.elements["tzBaseUtcOffset"].value = baseUtcOffset;
// Find first day of DST (from 1/1/2016)
var dstDayOffset = 0;
if (janOffset != julOffset) {
var startDay = janOffset > baseUtcOffset ? 180 : 0; // if southern hemisphere, start 180 days into year
for (var day = startDay; day < 365; day++) if (-new Date(2016, 0, day + 1, 12).getTimezoneOffset() > baseUtcOffset) { dstDayOffset = day; break; } // noon
}
form.elements["tzDstDayOffset"].value = dstDayOffset;
C#
private TimeZoneInfo GetTimeZoneInfo(int baseUtcOffset, int dstDayOffset) {
// Converts client/browser data to TimeZoneInfo
// baseUtcOffset: minutes from UTC (non-DST)
// dstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
// Returns first zone info that matches input, or server zone if none found
List<TimeZoneInfo> zoneInfoArray = new List<TimeZoneInfo>(); // hold multiple matches
TimeSpan timeSpan = new TimeSpan(baseUtcOffset / 60, baseUtcOffset % 60, 0);
bool supportsDst = dstDayOffset != 0;
foreach (TimeZoneInfo zoneInfo in TimeZoneInfo.GetSystemTimeZones()) {
if (zoneInfo.BaseUtcOffset.Equals(timeSpan) && zoneInfo.SupportsDaylightSavingTime == supportsDst) {
if (!supportsDst) zoneInfoArray.Add(zoneInfo);
else {
// Has DST. Find first day of DST and test for match with sent value. Day = day offset into year
int foundDay = 0;
DateTime janDate = new DateTime(2016, 1, 1, 12, 0, 0); // noon
int startDay = zoneInfo.IsDaylightSavingTime(janDate) ? 180 : 0; // if southern hemsphere, start 180 days into year
for (int day = startDay; day < 365; day++) if (zoneInfo.IsDaylightSavingTime(janDate.AddDays(day))) { foundDay = day; break; }
if (foundDay == dstDayOffset) zoneInfoArray.Add(zoneInfo);
}
}
}
if (zoneInfoArray.Count == 0) return TimeZoneInfo.Local;
else return zoneInfoArray[0];
}
You can get this information from client to server (any web API call)
var timezoneOffset = new Date().getTimezoneOffset();
With the help of timezoneoffset details you can achieve the same. Here in my case i converted UTC DateTime to my client local datetime in Server side.
DateTime clientDateTime = DateTime.UtcNow - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
Click for code example
Take a look at this asp.net c# solution
TimeZoneInfo mytzone = TimeZoneInfo.Local;
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_TIMEZONE"] ;

How do you compare selector attributes in Testcafe?

I'm trying to compare the date of videos on a webpage to today's date. If the difference between the two dates is more than X days, report back as false.
The videos on the webpage have a tag in them which uses the format yyyy-mm-dd
I've got a selector set up to find the videos const videoDate = Selector('OPTA-video').withAttribute('data-secondary-time')
Now how do I set a variable to today's date and compare the two? I'm completely stuck!
I was using Katalon Studio before and here's the groovy script that did the same job:
String videoDate = WebUI.getAttribute(findTestObject('OPTA-video'), 'data-secondary_time')
LocalDate todaysDate = LocalDate.now()
LocalDate videoDateParsed = LocalDate.parse(videoDate, dtf)
if (ChronoUnit.DAYS.between(videoDateParsed, todaysDate) > 1) {
KeywordUtil.markFailed('The videos are 2+ days old.')
} else {
KeywordUtil.logInfo('The videos are up to date.')
}
You can use the getAttribute TestCafe method to access an attribute value. Then, parse the attribute value into the JavaScript Date object:
String videoDate = Selector('OPTA-video').getAttribute('data-secondary-time');
Date videoDateParsed = Date.parse(videoDate);
Date todaysDate = Date.now()
...
In the following thread you can find how to compare Date objects.
This is one of the scripts that I am using.
//getting your XPath test value into a string
String ann_time =
WebUI.getText(findTestObject("ObjectRepository/navigateTOElement/announcements_date"))
//converting time to simple date format
SimpleDateFormat sdf = new SimpleDateFormat('HH:mm')
Date sdf_anntime = sdf.parse(new String(ann_time))
//getting Current time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat('HH:mm')
dateFormatGmt.setTimeZone(TimeZone.getTimeZone('GMT'))
SimpleDateFormat dateFormatLocal = new SimpleDateFormat('HH:mm')
currDate = dateFormatLocal.parse(dateFormatGmt.format(new Date()))
// time gap in long format
long duration = currDate.getTime() - sdf_anntime.getTime()
//time gap to mins
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration)
//compare time gap with globale variable
if (diffInMinutes < GlobalVariable.News_updated_time) {
log.logInfo("system is getting updated,last updated "+ diffInMinutes + "min ago")
} else {
CustomKeywords.'errorMessage.logFailed.markStepFailed'('from 1 h, system was not updated')
log.logInfo('from '+ diffInMinutes+ 'h, system was not updated')
}

Calculate the difference between two dates in React Native

I need to calculate the difference between two dates in days
i bring today date: new Date().toJSON().slice(0, 10) = 2019-04-17
and the other date in the same form
var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime(); //Future date - current date
var daysTill30June2035 = Math.floor(msDiff / (1000 * 60 * 60 * 24));
console.log(daysTill30June2035);
You can implement it yourself, but why would you? The solution to that already exists, and somebody else has taken care (and still is taking care) that it works as it should.
Use date-fns.
import differenceInDays from 'date-fns/difference_in_days';
If you really want to bash your head, you can get difference in milliseconds and then divide by number of milliseconds in a day. Sounds good to me, but I'm not 100% sure if it works properly.
const differenceInDays = (a, b) => Math.floor(
(a.getTime() - b.getTime()) / (1000 * 60 * 60 * 24)
)
If you manipulate many dates, maybe an external library like moment.js could be useful. There are multiple add-ons like the date range one.
Once installed, you need to create a range
const start = new Date(2011, 2, 5);
const end = new Date(2011, 5, 5);
const range = moment.range(start, end);
Then could get the difference by doing something like
range.diff('months'); // 3
range.diff('days'); // 92
range.diff(); // 7945200000
Hope it could be useful :)
var d1 = new Date("2019/04/17") //firstDate
var d2 = new Date("2011/02/01") //SecondDate
var diff = Math.abs(d1-d2); //in milliseconds
Use differenceInDays, parseISO from "date-fns"
import DateTimePicker from "#react-native-community/datetimepicker";
import { differenceInDays, parseISO } from "date-fns";
let day = differenceInDays(
parseISO(your end date),
parseISO(yout first Date)
);
console.log("differenceInDays",differenceInDays)

Express Validatior - How Do I Break The Validation Chain?

I have a date field that I want to ensure is in a valid format and if so is the user over 18. The format is YYYY-MM-DD.
Here is one of my validators - the one that is failing:
body('birthday', 'Date format should be: YYYY-MM-DD')
.isRFC3339()
.custom(date => {
const over18 = moment().diff(date, 'years') >= 18;
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),
Currently what happens is if the date is not a RFC3339 date the validation chain continues. This is problematic because moment produces an error if I pass an ill formatted date.
How do I break the chain after the call to .isRFC3339() so that if the date is invalid the custom validator will not run? I couldn't find anything in the docs
You can use momentjs strict mode together with String + Format parsing using moment.ISO_8601 (or moment.HTML5_FMT.DATE) special formats.
Your code could be like the following:
body('birthday', 'Date format should be: YYYY-MM-DD')
// .isRFC3339() // no more needed
.custom(date => {
const mDate = moment(date, moment.ISO_8601, true);
const over18 = moment().diff(mDate, 'years') >= 18;
if(!mDate.isValid()) {
return Promise.reject('Date is not YYYY-MM-DD');
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),