I'm using Rails and MongoMapper as my working platform.
I want to generate a custom key with the help of month and year. The possible format would be YYYYMM####,
YYYY is current YEAR which I can get as Date.today.strftime("%Y")
MM is current Month Which I can get as Date.tody.strftime("%m")
After that ### is incremented integer value
I get the last job with the code
jobForLastnum = Job.last(:order => :_id.desc)
lastJobNum = jobForLastnum.job_number
Now my question is I received the job_number as '201305100'
I want to split it with custom length like, ['2013','05','100']
I know how to split a string in ruby and I successfully did that but i got result as individual character like
['2','0','1','3','0','5','1','0','0']
With the help of this I could retrieve the year:
lastJobNum.to_s[0,4]
With the help of this I got the month:
lastJobNum.to_s[4,2]
But after that there is custom length string. How can I get all the data in a single array?
You can simply use ranges:
c = "2013121003"
[c[0..3], c[4..5], c[6..-1]]
You can also use String#unpack:
"20131210034".unpack("A4A2A*")
Or with regexp as suggested by tessi, using String#scan:
c = "2013121003"
c.scan(/(\d{4})(\d{2})(\d+)/)
In all cases, this will return an array with the year, month, and job id as strings.
A regexp can help you here.
jobNumber = 201305100
year, month, job_id = jobNumber.to_s.match(/(\d{4})(\d{2})(\d*)/)[1..3]
First, we convert the jobNumber to a String. Then we throw a regexp at it. The regexp has three capture groups ((\d{4}) four numbers for the year, (\d{2}) two numbers for the month, (\d*) any remaining number for the job_id).
The job_number.to_s.match(...) returns a MatchData object, which we can access by its first three capture groups with [1..3] (see the documentation).
Finally, we assign the resulting Array to our variables year, month, and job_id.
year
#=> 2013
month
#=> 05
job_id
#=> 100
Related
I'm building an iOS app where I want to retrieve all the values from my database between two dates that the user picks. So for example, I want all the rows from the 1st of March to the 5th of March. Would look something like
SELECT * FROM MAIN WHERE DATE = '01/03/2020' AND ENDS ='05/03/2020'
So from that I would hope to retrieve all data from the 1st,2nd,3rd,4th and 5th of march. Any ideas on how to do this?
Thank you
Try to use comparison operators like:
DATE >= '01/03/2020' AND DATE <= '05/03/2020'
There are two issues:
Date types:
As Datatypes In SQLite Version 3 says:
2.2. Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
So storing dates in a dd/MM/yyyy format (using the DateFormatter capitalization convention) is problematic because in the absence of a native date type, it’s going to store them as strings, and therefore all comparisons will be done alphabetically, not chronologically, sorting values like 03/10/2009 (or nonsense strings like 02foobar, for that matter) in between the strings 01/05/2020 and 05/05/2020.
If, however you store them as yyyy-MM-dd, then it just so happens that alphabetical comparisons will yield chronologically correct comparisons, too.
SQL syntax:
Once you have your dates in your database in a format that is comparable, then if you have all of your dates in a single column, you can use the BETWEEN syntax. For example, let’s say you stored all of your dates in yyyy-MM-dd format, then you could do things like:
SELECT * FROM main WHERE date BETWEEN '2020-03-01' AND '2020-03-05';
But needless to say, you can’t use this pattern (or any comparison operators other than equality) as long as your dates are stored in dd/MM/yyyy format.
If you want to show all the data that has values of column "date" between this two dates then:
Select *
from MAIN
where `date` between '01.03.2020' and '05.03.2020';
If you want to show all the data that has values of column "ends" between this two dates then:
Select *
from MAIN
where ends between '01.03.2020' and '05.03.2020';
If you want to show all the data that has values of columns "date" and "ends" between this two dates then:
Select *
from MAIN
where ends between '01.03.2020' and '05.03.2020'
and `date` between '01.03.2020' and '05.03.2020';
Here is a demo
I have a rails and react app and i noticed i have been logging the date into my backend as day/month/year instead of month/day/year. what is the best way to go into my rails backend and fix theses dates. For example I want to turn "7/3/2018" into "3/7/2018" (yes they are strings).
I'm assuming i would start off with something like this:
date = "7/3/2018"
date.split("/")
but then how will i swap the values? Or is there a better way to do this other than to use split?
You can get each value in the array from the splitted string, and then interpolate them in a new string in the order you need:
date = '7/3/2018'
month, day, year = date.split('/')
p "#{day}/#{month}/#{year}" # "3/7/2018"
Other way could be using Date#parse and strftime to handle the format output:
require 'date'
date = '7/3/2018'
p Date.parse(date).strftime('%m/%d/%Y') # "03/07/2018"
I have a db table events, it has a column dates which stores arrays of dates like this
eg: ["2017-05-19","2018-04-19","2005-04-19","2017-06-19","2015-04-9"]
say im given month value, 05. I should compare months of dates present in dates column for each event and return list of all events where it has dates containing month exactly 05.
so, if event1 and event2 has month 05 in array of dates, return event1 and event2.
I tried this, got confused. where("dates #> ARRAY[?]::varchar[]", don't_know_what_to_give_here)
This is untested, but you can use the postgres array_to_string method and then the LIKE operator on the resulting string.
select *
from your_table_name
where array_to_string(dates, ',') LIKE '%-05-%'
With Rails
Model.where("array_to_string(dates, ',') LIKE '%-?-%'", month)
# just make sure month has a leading zero e.g. 01 instead of just 1
Rails 4.1
I'm am trying to add a date attribute to an ActiveRecord object by handing it a string and I'm getting some strange results:
t = MyClass.new
t.StartDate = "1/11/2015" #date is loaded as expected
t.StartDate = "1/12/2015" #date is loaded as expected
t.StartDate = "1/13/2015" #ArgumentError: argument out of range
The same appears to hold true for any day of the month > 12. What am I missing here? Yes, I could parse the string into a Date object (and I've been able to do this successfully with the same problem dates as strings), but why does my method work for some valid dates and not others?
Your dates are formatted with day/month/year when your trying to use it like month/day/year
This is why you can't go further than 12 because 12 is representing the month
I need to know how would I check if my given value is between two closest array's members. For example I have an array of dates with the date of week start in given period of time. And I need to check if my given date is in one of its week. For example:
2015-11-02
2015-11-09
2015-11-16
2015-11-23
And my given value is 2015-11-11 for example. How should I check if it is one of these weeks date? Thanks for help.
%w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).any? do |date|
date.to_date.cweek == Date.today.cweek
end
And here is what this does:
First, you have an array of strings, you use any? to loop through it and check if any fulfils a requirement, then you cast you date strings into actual dates, and cweek gives you the number of a week in the year. Date.today gives you today's date.
Instead of Date.today.cweek you can use '2015-11-11'.to_date.cweek.
The loop above returns boolean; you could also get an array of values that fulfil a condition like this:
new_array = %w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).map do |date|
date.to_date.cweek == '2015-11-11'.to_date.cweek
end.compact
Resources:
Date class on ruby-doc.org
Date & Time in Ruby on tutorialspoint.com
UPDATE
If you want to get from the database only records with a date from particular week, this is how you could do it:
my_date = '2015-11-11'.to_date
matching_records = MyResource.where( date: my_date.beginning_of_week..my_date.end_of_week )
The assumptions are that you have a model MyResource, and that it has a column date. What this does is returns a relation with all the records that have dates from the same week as my_date.
Assuming your dates array is sorted:
date >= dates.first && date <= dates.last
If you're dealing with strings, you can "require 'date'" and transform your strings to dates ("Date.parse('2001-02-03')").
As others have suggested, you can then see if your date is between the first and last entry of your list.
If the real list is sorted and each entry is one week apart, then you can easily find where in the list your guy is.
E.g., say the list is [date_0, date_1, date_2, ..., date_k] (all 1 week apart), and you're given a test_date between date_0 and date_k. Then (test_date.jd - date_0.jd)/7 gives you the index of the date in your list that is <= test_date.