How to use Time Data type only in Rails? - mysql

I use time as datatype in my rails migration but when I am retrieving it in model
it includes date. I wanted to be able to compute time difference without date.
Any way I can do to make my model return time only ?
I wanted this 03:15:00 not this 2000-01-01 05:54:42

If you want to convert a Datetime object into a Time object, you can use Time.parse.
date_and_time = Time.now # 2000-01-01 05:54:42
time_only = Time.parse(date_and_time) # 05:54:42

If you use the time data type for a column in your database migration you should be fine. Rails fills the missing fields (in this case year, month, day) with default values since the data type requires them. Since all responses get these default values you should be able to calculate time differences without date since all values have the same default value. If you want to get the time as string back in the format you want you can use #strftime method.
Eg:
time.strftime('%H:%M:%S')

Related

Transform the field values pentaho(kattle) and store it in standard format in any table

I want to transform the value of fields name and Date using pentaho(kattle) and store it in standard format in any table.
For example
id,name,f_n,Date
1,j_vick,03-05-2015
2,jo_vick,04,08,2016
3,Arn_jonnn_vick,05,07,2017
Now I want to transform it using pentaho(kattle) IDE and store it in data base like below:
id,name,Date
1,john_vick,03/05/2015
2,john_vick,04/08/2016
3,Arn_john_vick,05/07/2017
I don't want the transformation steps concern with extraction database storage.
The date format is just some clothing of a value. Just read it with Kettle and store it as is. The database will store it in its proper internal binary format anyway.
Unless, you have to store them explicitly as varchar. In that case, use the Metadata tab of the Select Value step. Define your column as Date and specify the format as dd/MM/yyyy or MM/dd/yyyy. It will be kept internally as a Date, and converted into a String with the selected format at the last moment.
You also seam to have an other problem: the day, month and year are in three columns. The easiest way is to use a Modified Java Script Value step, in which you define a new column date = new Date(year, month, year), with type Date, and let Kettle handle with the format.
Maybe you have mixed input, in which case you can use a Filter or a Swtich step, based on weather you have something in the day and month column.
When that is done, you can make a job that runs the transformation on all the tables. You have an example in the sample/jobs/process all tables furnished with the Pentaho Data Integrator (aka Kettle).

How to separate time from datetimepicker vb.net

I have one datetimepicker which custom format MM/dd/yyyy h:mm tt
I have database and has a column "Date_Time" the value of the DateTimePicker is saved to the column Date_Time formatted like this MM/dd/yyyy h:mm tt
now i want to get the Time only not the entire value of datetimepicker just the hh:mm tt from the column Date_Time
SORRY FOR MY GRAMMAR
How about DateTime.TimeOfDay?
It returns the time that has elapsed since midnight (which is what h:mm tt stands for in your code).
Dim Time As TimeSpan = DateTimePicker1.Value.TimeOfDay 'Would return for example 3:14 PM
The answer above is right.
If you need to get time string, you can use also another way, which includes a formating:
Dim myTimeString = DateTimePicker1.value.ToString("hh:mm")
You can do that for any part of the DateTime value.
You are heading for a new problem. If you zero out the Date portion and store the result to a DateTime column, you will end up storing something like: 0001-01-01 16:43:12. A column defined as DateTime will always have a Date, as will a DateTime variable.
The first problem may be getting MySQL to accept a non-Date in a DateTime column. Using a column defined as DateTime(3), mine throws a generic fatal error exception trying to store just a TimeSpan to it:
cmd.Parameters.Add("#p3", MySqlDbType.DateTime).Value = DateTime.Now.TimeOfDay
cmd.ExecuteNonQuery()
If MySqlDbType.Time is used as the type, I get an exception that the time is an invalid value for the column...and it is.
If you manage to store it somehow, the next problem will be when/if you want to put that value back in a DateTimePicker: the minimum date you can enter is 1/1/1753 (first full year of the current calendar). So your DateTime var with the Date zeroed out wont work. You'll first have to restore the date portion, but the Date, Year etc are all readonly.
Solution 1
Define the column as Time(0) which will store hours, minutes and seconds. Use the value in the parens to specify fractional seconds, for instance Time(3) will also store milliseconds. When you read the data, store it to a TimeSpan.
Then in your UI use a different control, otherwise you have the same problem - adding some Date data to it to make it usable in a DateTimePicker
Solution 2
Use a DateTimePicker and a DateTime column, but just ignore the Date portion in your code. This will allow you to use what is in the Database as is with the control.
You can get the time selected with DateTime.TimeOfDay but storing and reusing it may be problematic.

How to display datetime form mysql using CakePHP 3.0

I would like to ask how to add datetime ('Y-m-d h:i:s') format field for the SQL.
The name of my table is groups, the name of the field is date_add
i am using cake PHP 3, i want to use the timezone Australia/Perth but i don't know how to begin.
I successfully displayed added my date using
$group->date_add = date("Y-m-d h:i:s");
However, the result for the time is not correct with the timezone.
Datetime in PHP in general
Per the documentation of DateTime you can use all options available for the date() functions for formatting. Your main mistake in the formatting is the difference betweetn a y and a Y being the difference between a year in two and a year in four numbers.
Secondly you say you want to add the correct time zone. This is a bit odd however since you always want to add the same time zone. If you want to convey the fact that all your dates are Australia/Perth as information why do you not simply add that text after it?
If you mean this is a problem since you store the information in a different time zone to begin with and thus have a conversion problem you can set the correct time zone on the DateTime object itself. But you need to be sure the DateTime object is constructed with the correct original time zone to begin with. Observe the following code for an explanation:
<?php
$DateTime = new DateTime(); // This is now Europe/Amsterdam for my laptop
var_dump($DateTime->format('dmY h:i e'));
// result of var_dump is: string(31) "13102015 12:00 Europe/Amsterdam"
$DateTime->setTimeZone(new DateTimeZone('Europe/London'));
var_dump($DateTime->format('dmY h:i e'));
// result of var_dump is: string(28) "13102015 11:00 Europe/London"
Take aways:
e is the format modifier for the time zone
Conversion of time zones is possible with PHP's DateTime object. Find out what your default time zone is on your current PHP installation to see if you need to convert or not. See information on the date.timezone setting here: http://php.net/manual/en/datetime.configuration.php
Cake 3.0 specific
As Oops D'oh pointed out in the comments there are a lot of CakePHP specific things to know as well. Since he added an excellent part concerning that I suggest you read that as well.

rails datetime field in edit form says UTC

I have a datetime field and the value is stored in mysql like this:
2014-08-26 16:00:00
When user selects datetime, they select it from a jquery datetime popup. And its inserted into text field and sent to the server at which point it is parsed like this:
def date_start=(s)
datetime = parse_datetime s
write_attribute :date_start, datetime
end
def parse_datetime(s)
DateTime.strptime(s,'%m/%d/%Y %I:%M %p')
end
And then inserted into the database. Now when the user edits the form, the datetime is displayed in the text field, but it is displayed like this:
2014-08-26 16:00:00 UTC
Why does it say UTC there (the record is retrieved and stored local time) and how can I get rid of that?
It's considered good practice to store timestamps in your database as UTC time, regardless of which timezone they were originally (so they can be accurately compared and prevent messes that usually arise when things aren't consistent).
Active Record takes care of this by doing the conversion automatically. That means that when a user selects a datetime, you have to ensure it's given the right timezone in Rails/Ruby when it is inputted, using Time.use_zone() or something similar. And similarly when displaying it after retrieving from the database. You'll need some way to retrieve the user's local timezone (Javascript or a manually selected profile option).
As an aside, if you want to set the default timezone for your application to something other than UTC, then you can change the config.time_zone option in application.rb. Note that the database will still store things in UTC, it just allows you to set a sensible default timezone for datetime input and output (i.e. a default timezone for Active Record to convert to/from). It won't help with individual user datetimes though, unless all your users reside in the same timezone.
You shouldn't override writer at all. Rails shoudl handle it properly.
In form show datetime like this:
f.text_field :date_start, (f.object.date_start.strftime('%m/%d/%Y %I:%M %p') if f.object.date_start ) ...
or make a method
def form_date_start
date_start.strftime('%m/%d/%Y %I:%M %p') if date_start
end
and in form
f.text_field :date_start, f.object.form_date_start

Getting records from MySQL based on a DateTime column ignoring the time portion using JPA along with Joda-Time

How to filter rows from MySQL database ignoring the time portion of a given DateTime field in MySQL using JPA?
For example, the following segment of code counts the number of rows from a database table that lie between the two dates given in a column of type DateTime in MySQL.
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Long>criteriaQuery=criteriaBuilder.createQuery(Long.class);
Root<Discount> root = criteriaQuery.from(entityManager.getMetamodel().entity(Discount.class));
criteriaQuery.select(criteriaBuilder.countDistinct(root));
DateTimeFormatter dateTimeFormatter=DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa");
DateTime firstDate = dateTimeFormatter.parseDateTime("01-Oct-2013 11:34:26 AM").withZone(DateTimeZone.UTC);
DateTime secondDate = dateTimeFormatter.parseDateTime("31-Oct-2013 09:22:23 PM").withZone(DateTimeZone.UTC);
criteriaQuery.where(criteriaBuilder.between(root.get(Discount_.discountStartDate), firstDate, secondDate));
Long rowCount = entityManager.createQuery(criteriaQuery).getSingleResult();
The two parameters firstDate and secondDate will be in turn dynamic.
How to rewrite this query so that the comparison does not include the time portion in the SQL query which is to be delegated to MySQL.
The column discount_start_date in the entity Discount is designated as follows.
#Column(name = "discount_start_date")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime discountStartDate;
Seems like you are working too hard.
(a) Apparently, MySQL offers a DATE() function that extracts the date portion of a date-
time field. (I'm a Postgres guy, and don't know MySQL.) You could pursue an approach using that function call as part of your query. But I'm guessing it would faster performance if you first obtained your start and stop time by calculating with Joda-Time in Java before executing the SQL query, as seen below.
(b) Why not do this with a simple SQL query, a two criteria SELECT?
In pseudo-code:
Find Discount records that go into effect from the moment this month starts up until the moment the next month starts.
Use Java and Joda-Time to give you the start & stop values.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
Caution: Above code uses default time zone. You should specify a time zone in the constructor.
MySql seems to lack sophisticated time-date handling with time zones etc. So I suppose you would convert those time zoned DateTime objects to UTC.
org.joda.time.DateTime startOfThisMonthInUtc = startOfThisMonth.toDateTime( org.joda.time.DateTimeZone.UTC );
org.joda.time.DateTime startofNextMonthInUtc = startofNextMonth.toDateTime( org.joda.time.DateTimeZone.UTC );
Then do what you do to get date-time values for MySQL.
Then form a query that looks something like this… (Note the use of >= versus < without the Equals sign.)
SELECT title_, amount_, start_date_
FROM discount_
WHERE discount_.start_datetime_ >= startOfThisMonthFromJodaTime
AND discount_.start_datetime_ < startOfNextMonthFromJodaTime
;
When working with date and time, it's generally better to work with the first moment of the day, first moment of the first day of month, etc. rather than try to find the last moment or end time. So my query is based on the idea of find rows whose values go up to, but do not include, the moment after the time frame in which I'm interested.