I need to validate the timezone value that I have been given and that too i want to parse it in a particular date format and time zone should be "-1300 to 1400" (+/-HHMM).
I have tried with some, but I'm not able to get validate the time zone.
If timezone = "-1260"(it's a invalid value) , then it should print "Invalid time zone" but its not behaving like that.
Here's the code I've tried - https://play.golang.org/p/kbTsQAW-f-_r
var validTZ = regexp.MustCompile(`[+-][0-9]{4}$`)
tz:= "-1260"
tzInt, _ := strconv.Atoi(tz)
t1 := time.Now().UTC()
formattedDate := t1.Format("2006-01-02T15:04:05.000")
formattedDate += tz
_,err:=time.Parse("2006-01-02T15:04:05.000-0700",formattedDate)
if !validTZ.MatchString(tz) || (tzInt >= -1300 && tzInt <= 1400) || err != nil {
fmt.Println("Invalid time zone")
}
It is true that tz (1260) is tzInt >= -1300 && tzInt <= 1400
But your code is:
!(tzInt >= -1300 && tzInt <= 1400)
The ! negates the condition, making it tzInt < -1300 || tzInt > 1400: that is why "Invalid time zone" is not displayed.
As commented by the OP, you can also print that error based on a more precise regex:
^[+-]([0-9]{2})([0-5]{1})([0-9]{1})$
That will prevent any xx6y value.
Related
I want to validate a time given in string format as “YYYY-MM-DD HH:MM:SS” and want to check which is latest date.
I can able to convert given string into seconds and compare them as follows.
std::string dateStr1 = "2016-06-31 02:00:58"; // June 31 2016 does not exist
std::string dateStr2 = "02:00:00";
std::istringstream date_s(dateStr1);
struct tm date_c;
date_s >> std::get_time( &date_c, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds1 = std::mktime( & date_c );
std::istringstream date_s2( "2001-10-01 02:10:00" );
struct tm date_c2;
date_s2 >> std::get_time( &date_c2, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds2 = std::mktime( & date_c2 );
if(seconds1 > seconds2){
cout<<" Seconds1 is greater "<<seconds1<<endl;
}else{
cout<<" Seconds2 is greater "<<seconds2<<endl;
}
Answer: Seconds1 is greater 1467334858
Problem: this method converts a date that doesn’t exist.
( the date given in dateStr1 is doesn’t exist but mktime() makes time for this date. )
How to check whether a date exist or not?
From the cppreference documentation of mktime:
If the conversion is successful, the time object is modified. All
fields of time are updated to fit their proper ranges. time->tm_wday
and time->tm_yday are recalculated using information available in
other fields.
You can use this to check if the date was valid or not. If it was invalid, the tm struct will be modified by mktime:
std::string dateStr1 = "2016-06-31 02:00:58"; // June 31 2016 does not exist
std::string dateStr2 = "02:00:00";
std::istringstream date_s(dateStr1);
struct tm date_c, date_c_cmp;
date_s >> std::get_time( &date_c, "%Y-%m-%d %H:%M:%S" );
date_c_cmp = date_c; // store original to compare later
std::time_t seconds1 = std::mktime( & date_c );
if(date_c.tm_year != date_c_cmp.tm_year // compare with original
|| date_c.tm_mon != date_c_cmp.tm_mon
|| date_c.tm_mday != date_c_cmp.tm_mday
|| date_c.tm_hour != date_c_cmp.tm_hour
|| date_c.tm_min != date_c_cmp.tm_min
|| date_c.tm_sec != date_c_cmp.tm_sec)
std::cout << "invalid" << std::endl;
std::istringstream date_s2( "2001-10-01 02:10:00" );
struct tm date_c2;
date_s2 >> std::get_time( &date_c2, "%Y-%m-%d %H:%M:%S" );
std::time_t seconds2 = std::mktime( & date_c2 );
if(seconds1 > seconds2){
std::cout<<" Seconds1 is greater "<<seconds1<<std::endl;
}else{
std::cout<<" Seconds2 is greater "<<seconds2<<std::endl;
}
I am trying to order by start date(s.StartDate). Below is my code so far, my understanding is that I should be adding .orderby(s.StartDate) somewhere but I don't think I'm even taking the correct route now as I have tried many ways.
var query = from s in context.SessionSearch
where s.Children == 0 && s.IsPublic == isPublic
select s;
var query = from s in context.SessionSearch
where s.Children == 0 && s.IsPublic == isPublic
if (startDate != null)
{
query = query.Where(s => s.StartDate >= startDate && s.StartDate <= endDate);
}
You should be able to start with the "without startdate" option - you have a couple of options here - either declare the type of the query specifically:
IQueryable<SessionSearch> query = from s in context.SessionSearch
where s.Children == 0 && s.IsPublic == isPublic
order by s.StartDate
select s;
And then as you've tried, add the additional where clause to the query if there's a start date passed in:
query = query.Where(s => s.StartDate >= startDate && s.StartDate <= endDate);
This means that you would not be able to add further ordering via the ThenBy methods.
Alternatively, you can add the order by clause after you've finished adding the where clauses:
var query = from s in context.SessionSearch
where s.Children == 0 && s.IsPublic == isPublic
select s;
if (startDate != null) {
query = query.Where(s => s.StartDate >= startDate && s.StartDate <= endDate);
}
query = query.OrderBy(s => s.StartDate);
Props to JonSkeet for pointing these out.
I have a problem. I want to build a dynamic LINQ query like this:
var result = from li in datacTx.LIs
where
(((StartDate != null) && (StartDate.Date != DateTime.MinValue)) ? li.Available <= StartDate.Date : true) &&
(((EndDate != null) && (EndDate.Date != DateTime.MinValue)) ? li.Expire <= EndDate.Date : true)
select new
{
A,
B,
C,
D
};
Before calling this query I am intializing the StartDate and EndDate with:
StartDate = DateTime.MinValue;
EndDate = DateTime.MinValue;
The problem is that the branch of "if" is always wrong I never can get the "true" branch if the StartDate and EndDate are having MinValue.
Try using a simpler condition:
where ((StartDate == DateTime.MinValue || li.Available <= StartDate.Date) &&
(EndDate == DateTime.MinValue || li.Expire <= EndDate))
However, if I were to implement something like this, I would actually create the query dynamically:
var query = datacTx.LIs;
if(StartDate != DateTime.MinValue)
query = query.Where(li => li.Available <= StartDate.Date);
if(EndDate != DateTime.MinValue)
query = query.Where(li => li.Expire <= EndDate .Date);
var result = query.Select(x => new { A, B, C, D });
the following query works ok if you comment out either the SinceID or the MaxID clause, but when both are included a "bad url" exception is generated.
var maxId = ulong.MaxValue;
var sinceId = (ulong)341350918903701507;
var searchResult =
(
from search in ctx.Search
where search.Type == SearchType.Search &&
search.ResultType == ResultType.Mixed &&
search.Query == "red wedding" &&
search.SinceID == sinceId &&
search.MaxID == maxId &&
search.IncludeEntities == false &&
search.Count == 200
select search).SingleOrDefault();
If you look at the query result in Fiddler, you'll see that the response is:
{"errors":[{"code":195,"message":"Missing or invalid url parameter"}]}
I can't respond to why Twitter wouldn't accept the query with both SinceID and MaxID. However, the query is formed correctly and there isn't any documentation describing constraints on the relationship between these two parameters for this particular scenario. The purpose of the MaxID is to be the id of the highest tweet to return on the next query. Both MaxID and SinceID are intended to help you page through data. I wrote a blog post on how to do this:
Working with Timelines with LINQ to Twitter
I seem to have the same problem as you are, so the only solution I have was to do it manually, so first I retrieved the the first list setting the sinceId value to the one I have like this:
var searchResult =
(
from search in TwitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == query &&
search.Count == pageSize &&
search.IncludeEntities == true &&
search.ResultType == ResultType.Recent &&
search.SinceID == sinceId
select search
).SingleOrDefault<Search>();
resultList = searchResult.Statuses;
Then I have to search for other tweets (the case when new tweets count is more the pageSize) so I had a while loop like this:
ulong minId = ulong.Parse(resultList.Last<Status>().StatusID) - 1;
List<Status> newList = new List<Status>();
while (minId > sinceId)
{
resultList.AddRange(newList);
searchResult =
(
from search in TwitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == query &&
search.Count == pageSize &&
search.IncludeEntities == true &&
search.ResultType == ResultType.Recent &&
search.MaxID == minId &&
search.SinceID == sinceId
select search
).SingleOrDefault<Search>();
newList = searchResult.Statuses;
if (newList.Count == 0)
break;
minId = ulong.Parse(newList.Last<Status>().StatusID) - 1;
}
Now for some reason here you can use both sinceId and maxId.
Just in case anyone else comes across this, I encountered this issue when the MaxId was an invalid Tweet Id.
I started off using zero but ulong.MaxValue has the same issue. Switch it out with a valid value and it works fine. If you're not using SinceId as well it seems to work fine.
I used to get same error "Missing or invalid url parameter", but as per Joe Mayo's solution, I have additionally added if(sinceID < maxID) condition before do while loop, because the query throws above error whenever maxID is less than sinceID, I think which is incorrect.
if (sinceID < maxID)
{
do
{
// now add sinceID and maxID
searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "from:#" + twitterAccountToDisplay + " -retweets" &&
search.Count == count &&
search.SinceID == sinceID &&
search.MaxID == maxID
select search)
.SingleOrDefaultAsync();
if (searchResponse == null)
break;
if (searchResponse.Count > 0 && searchResponse.Statuses.Count > 0)
{
newStatuses = searchResponse.Statuses;
// first tweet processed on current query
maxID = newStatuses.Min(status => status.StatusID) - 1;
statusList.AddRange(newStatuses);
lastStatusCount = newStatuses.Count;
}
if (searchResponse.Count > 0 && searchResponse.Statuses.Count == 0)
{
lastStatusCount = 0;
}
}
while (lastStatusCount != 0 && statusList.Count < maxStatuses);
//(searchResponse.Count != 0 && statusList.Count < 30);
}
How can I convert the following query in a Linq with Lambda ?
SELECT DISTINCT Registro, COUNT(Registro) as qnt
FROM XML_Relatorio
WHERE Arquivo = 'redenet.xml'
AND TipoErro <> 'Imovel Inserido'
AND TipoErro <> 'TI'
AND DataHora BETWEEN '01-01-2012' AND '02-01-2012'
GROUP BY Registro
ORDER BY Registro
I'm trying the following code, but I need some help to build the LINQ with Lambda
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI");
Supposing the DataHora field is of Date or DateTime type.
// parse the strings to datetime
var start = DateTime.Parse("01-01-2012");
var end = DateTime.Parse("02-01-2012");
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI"
// and compare them...
&& a.DataHora > start && a.DataHora < end);