PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Friday, November 25, 2022

[FIXED] Why is "and" operator not working in my python program?

 November 25, 2022     date, module, python, python-3.x, time     No comments   

Issue

The following is my code:

import greettime as gt

if int(gt.now.strftime("%H")) < 12:
    print("Good Morning, Rudra!")
elif int(gt.now.strftime("%H")) >= 12 and int(gt.now.strftime("%H")) < 17:
    print("Good Afternoon, Rudra!")
elif int(gt.now.strftime("%H")) >= 17 and int(gt.now.strftime("%H")) < 0:
    print("Good Evening, Rudra!")

print(int(gt.now.strftime("%H")))

and the file named greettime is:

import datetime as dt
now = dt.datetime.now()

This code is not producing any output.It is producing output if the "and" part is commented out. What is the error here? I am a student and learning python therefore asking for pardon if there is a presence of any simple silly mistake


Solution

Your code compares the time so that it's...

* less than 12
* greater than-equal to 12 and less then 17
* greater than-equal to 17 and less than 0

That last condition doesn't work because how is a number going to be greater than 17 and also less than 0? It doesn't work, and Python datetime also only supports hours from 0..23.

If you just to print Good Morning if it's midnight - noon, then Good Afternoon from noon to 5 PM, and then Good Evening otherwise, you can just do this and scrap the final comparison cases and replace it with a bare else, because you've already covered morning and afternoon hours.

from datetime import datetime

now = datetime.now()

if now.hour < 12:
    print("Good Morning, Rudra!")
elif now.hour >= 12 and now.hour < 17:
    print("Good Afternoon, Rudra!")
else:
    print("Good Evening, Rudra!")

print(now.hour)

You'll also notice I got rid of your strftime conversions because you can access the hour property on datetime objects directly.



Answered By - wkl
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 1, 2022

[FIXED] What is the fastest way to sum 2 matrices using Numba?

 November 01, 2022     multithreading, numba, numpy, performance, time     No comments   

Issue

I am trying to find the fastest way to sum 2 matrices of the same size using Numba. I came up with 3 different approaches but none of them could beat Numpy. Here is my code:

import numpy as np
from numba import njit,vectorize, prange,float64
import timeit
import time

# function 1: 
def sum_numpy(A,B):
    return A+B

# function 2: 
sum_numba_simple= njit(cache=True,fastmath=True) (sum_numpy)

# function 3: 
@vectorize([float64(float64, float64)])
def sum_numba_vectorized(A,B):
    return A+B

# function 4: 
@njit('(float64[:,:],float64[:,:])', cache=True, fastmath=True, parallel=True)
def sum_numba_loop(A,B):
    n=A.shape[0]
    m=A.shape[1]
    C = np.empty((n, m), A.dtype)

    for i in prange(n):
        for j in prange(m):
            C[i,j]=A[i,j]+B[i,j]
  
    return C

#Test the functions with 2 matrices of size 1,000,000x3:
N=1000000
np.random.seed(123)
A=np.random.uniform(low=-10, high=10, size=(N,3))
B=np.random.uniform(low=-5, high=5, size=(N,3)) 

t1=min(timeit.repeat(stmt='sum_numpy(A,B)',timer=time.perf_counter,repeat=3, number=100,globals=globals()))
t2=min(timeit.repeat(stmt='sum_numba_simple(A,B)',timer=time.perf_counter,repeat=3, number=100,globals=globals()))
t3=min(timeit.repeat(stmt='sum_numba_vectorized(A,B)',timer=time.perf_counter,repeat=3, number=100,globals=globals()))
t4=min(timeit.repeat(stmt='sum_numba_loop(A,B)',timer=time.perf_counter,repeat=3, number=100,globals=globals()))

print("function 1 (sum_numpy): t1= ",t1,"\n")
print("function 2 (sum_numba_simple): t2= ",t2,"\n")
print("function 3 (sum_numba_vectorized): t3= ",t3,"\n")
print("function 4 (sum_numba_loop): t4= ",t4,"\n")

Here are the results:

function 1 (sum_numpy): t1= 0.1655790419999903

function 2 (sum_numba_simple): t2= 0.3019776669998464

function 3 (sum_numba_vectorized): t3= 0.16486266700030683

function 4 (sum_numba_loop): t4= 0.1862256660001549

As you can see, the results show that there isn't any advantage in using Numba in this case. Therefore, my question is:
Is there any other implementation that would increase the speed of the summation ?


Solution

Your code is bound by page-faults (see here, here and there for more information about this). Page-faults happens because the array is newly allocated. A solution is to preallocate it and then write within it so to no cause pages to be remapped in physical memory. np.add(A, B, out=C) does this as indicated by @August in the comments. Another solution could be to adapt the standard allocator so not to give the memory back to the OS at the expense of a significant memory usage overhead (AFAIK TC-Malloc can do that for example).

There is another issue on most platforms (especially x86 ones): the cache-line write allocations of write-back caches are expensive during writes. The typical solution to avoid this is to do non-temporal store (if available on the target processor, which is the case on x86-64 one but maybe not others). That being said, neither Numpy nor Numba are able to do that yet. For Numba, I filled an issue covering a simple use-case. Compilers themselves (GCC for Numpy and Clang for Numba) tends not to generate such instructions because they can be detrimental in performance when arrays fit in cache and compilers do not know the size of the array at compile time (they could generate a specific code when they can evaluate the amount of data computed but this is not easy and can slow-down some other codes). AFAIK, the only possible way to fix this is to write a C code and use low-level instructions or to use compiler directives. In your case, about 25% of the bandwidth is lost due to this effect, causing a slowdown up to 33%.

Using multiple threads do not always make memory-bound code faster. In fact, it generally barely scale because using more core do not speed up the execution when the RAM is already saturated. Few cores are generally required so to saturate the RAM on most platforms. Page faults can benefit from using multiple cores regarding the target system (Linux does that in parallel quite well, Windows generally does not scale well, IDK for MacOS).

Finally, there is another issue: the code is not vectorized (at least not on my machine while it can be). On solution is to flatten the array view and do one big loop that the compiler can more easily vectorize (the j-based loop is too small for SIMD instructions to be effective). The contiguity of the input array should also be specified for the compiler to generate a fast SIMD code. Here is the resulting Numba code:

@njit('(float64[:,::1], float64[:,::1], float64[:,::1])', cache=True, fastmath=True, parallel=True)
def sum_numba_fast_loop(A, B, C):
    n, m = A.shape
    assert C.shape == A.shape
    A_flat = A.reshape(n*m)
    B_flat = B.reshape(n*m)
    C_flat = C.reshape(n*m)
    for i in prange(n*m):
        C_flat[i]=A_flat[i]+B_flat[i]
    return C

Here are results on my 6-core i5-9600KF processor with a ~42 GiB/s RAM:

sum_numpy:                       0.642 s    13.9 GiB/s
sum_numba_simple:                0.851 s    10.5 GiB/s
sum_numba_vectorized:            0.639 s    14.0 GiB/s
sum_numba_loop serial:           0.759 s    11.8 GiB/s
sum_numba_loop parallel:         0.472 s    18.9 GiB/s
Numpy "np.add(A, B, out=C)":     0.281 s    31.8 GiB/s  <----
Numba fast:                      0.288 s    31.0 GiB/s  <----
Optimal time:                    0.209 s    32.0 GiB/s

The Numba code and the Numpy one saturate my RAM. Using more core does not help (in fact it is a bit slower certainly due to the contention of the memory controller). Both are sub-optimal since they do not use non-temporal store instructions that can prevent cache-line write allocations (causing data to be fetched from the RAM before being written back). The optimal time is the one expected using such instruction. Note that it is expected to reach only 65-80% of the RAM bandwidth because of RAM mixed read/writes. Indeed, interleaving reads and writes cause low-level overheads preventing the RAM to be saturated. For more information about how RAM works, please consider reading Introduction to High Performance Scientific Computing -- Chapter 1.3 and What Every Programmer Should Know About Memory (and possibly this).



Answered By - Jérôme Richard
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 18, 2022

[FIXED] How to hide events that happened today and have passed ? Symfony

 October 18, 2022     symfony, time     No comments   

Issue

In my Symfony project, I have created the table "event" and datatime field in it named start. In twig, I wish to filter and display upcoming events. So events that have passed would be visible any more.

At the moment, I used {% if event.start > date() %}. It worked to hide events that happened days before today. I wanted also to hide events that already happened today but currently it doesn't work when time has passed of the today's event.

How can I hide events that time already has passed ?


Solution

Here is a better solution (I precise that an address is given to events, and address has a "bigcity" registered, this why I am using LocationRepository) :

EventController.php

    #[Route('/events', name: 'events')]
    public function events(
        Request $request, 
        EventRepository $eventRepository, 
        CategoryRepository $categoryRepository,
        BigCityRepository $bigcityRepository,
        LocationRepository $locationRepository
    ){
        $category = $categoryRepository->findOneById($request->query->get('category'));
        $bigcity = $bigcityRepository->findOneById($request->query->get('bigcity'));
        $location = $locationRepository->findAll($request->query->get('location.bigcity'));

        $events = $eventRepository->findBy(['category' => $category, 'address' => $location]);
        return $this->render("front/events.html.twig", [
            'events' => $events,
            'category' => $category,
            'bigcity' => $bigcity
        ]);
    }


Answered By - Emilie Tossan
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 15, 2022

[FIXED] Why doesn't time.sleep work as with print end arguments?

 September 15, 2022     printing, python, time     No comments   

Issue

I am trying to use time.sleep() to pause in between print statements.

import time
def test():
    print("something", end="")
    time.sleep(1)
    print(" and ", end="")
    time.sleep(1)
    print("something")

When I use the end argument, the code waits before it starts to print. It should print, wait, print, wait, and print ("something, wait, and, wait, something"). However, when I use the end argument, it waits, and prints "wait something and something". This code works as I wanted it to without the end argumets.


Solution

Your output device is line-buffered and only flushes when a new line is output. Add flush=True as an additional parameter to print to force a flush to the output.



Answered By - Mark Tolonen
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, September 10, 2022

[FIXED] How to get current time and date in C++?

 September 10, 2022     c++, cross-platform, date, time     No comments   

Issue

Is there a cross-platform way to get the current date and time in C++?


Solution

Since C++ 11 you can use std::chrono::system_clock::now()

Example (copied from en.cppreference.com):

#include <iostream>
#include <chrono>
#include <ctime>    

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();
 
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);
 
    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s"
              << std::endl;
}

This should print something like this:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s


Answered By - Frederick The Fool
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, August 27, 2022

[FIXED] How to convert 0:00:00 to 00:00:00 time format in SQLite?

 August 27, 2022     csv, sql, sqlite, time     No comments   

Issue

I am trying to convert time format 0:00:00 to 00:00:00 from my CSV file in SQLite. I have tried using time() but it would delete a time with any hour of a single digit (for example: 8:09:09 would be deleted, but the time frame between 10:00:00-23:59:59 is kept). Is there a way to convert this time frame in SQLite or would it be easier to convert it in my CSV file? How would I convert the time format in my CSV file, if applicable? I hope this question is clear as I am new here. I posted my table and the code here to illustrate the issue I am facing.

Table 1:

ID BEFORE_DATE BEFORE_TIME AFTER_DATE AFTER_TIME
81 2020-01-03 18:01:09 2020-01-03 22:44:12
8 2020-05-09 8:01:09 2020-05-09 13:44:12
9 2020-02-09 16:09:23 2020-02-09 13:00:00

My goal:

Table 2

ID BEFORE_DATE BEFORE_TIME AFTER_DATE AFTER_TIME
81 2020-01-03 18:01:09 2020-01-03 22:44:12
8 2020-05-09 8:01:09 2020-05-09 13:44:12

The problem here is that ID 8 won't show. Instead, only ID 81 shows.

My current code:

CREATE TABLE table2 AS
from table1
SELECT *
FROM table1
WHERE BEFORE_DATE=AFTER_DATE AND TIME(BEFORE_TIME) < TIME(AFTER_TIME);

Solution

If the problem is only with the missing 0 from the hours part, you may check the length of the time string and add that missing 0 for times with length =7, try the following:

With Fixed_Times AS
(
  SELECT ID, BEFORE_DATE,
       Case When length(BEFORE_TIME)=7 Then ('0' || BEFORE_TIME) Else BEFORE_TIME End AS BEFORE_TIME,
       AFTER_DATE,
       Case When length(AFTER_TIME)=7 Then ('0' || AFTER_TIME) Else AFTER_TIME End AS AFTER_TIME
  FROM table1
)

SELECT * FROM Fixed_Times
WHERE BEFORE_DATE <= AFTER_DATE AND BEFORE_TIME < AFTER_TIME

See a demo from db<>fiddle.

To create another table and insert the results to it (as you did in your question), try the following:

CREATE TABLE table2 AS
With Fixed_Times AS
(
  SELECT ID, BEFORE_DATE,
       Case When length(BEFORE_TIME)=7 Then ('0' || BEFORE_TIME) Else BEFORE_TIME End AS BEFORE_TIME,
       AFTER_DATE,
       Case When length(AFTER_TIME)=7 Then ('0' || AFTER_TIME) Else AFTER_TIME End AS AFTER_TIME
  FROM table1
)
SELECT * FROM Fixed_Times
WHERE BEFORE_DATE <= AFTER_DATE AND BEFORE_TIME < AFTER_TIME;

See a demo.

To update the original table (table1) and fix the time format, try the following:

Update table1 set BEFORE_TIME =
       Case When length(BEFORE_TIME)=7 Then ('0' || BEFORE_TIME) Else BEFORE_TIME End,
       AFTER_TIME =
       Case When length(AFTER_TIME)=7 Then ('0' || AFTER_TIME) Else AFTER_TIME End;

See a demo.



Answered By - Ahmed
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 26, 2022

[FIXED] How to remove the date from time data when it is separated by a space?

 August 26, 2022     csv, python, spyder, time     No comments   

Issue

I have some data in a current .csv file that is space separated then ; separated. I get how to do the sep";" but the problem is the spaces. It looks a little like this:

Time; Age; etc
04-09-2003 17:06:39 ; 29 ; etc

I need to get the date removed so that in "Time" there is only the variable of time (ie. I don't need the system to look at the date at all as it is rather irrelevant).

How would I go about this? And is it reproducible for around 5000 bits of data?

Many thanks in advance!


Solution

after seperating the line with ';', just split each part again after each ' '.

datetime = "04-09-2003 17:06:39"
parts = datetime.split(' ')
print(parts[1])


Answered By - Cruik
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 30, 2022

[FIXED] How to check if a string value is in a correct time format?

 July 30, 2022     c#, string, time, validation     No comments   

Issue

Is there a possibility to check wether a string is in a valid time format or not?

Examples:
12:33:25 --> valid
03:04:05 --> valid
3:4:5    --> valid
25:60:60 --> invalid

Solution

Additional method can be written for the purpose of the string time format validation. TimeSpan structure has got TryParse method which will try to parse a string as TimeSpan and return the outcome of parsing (whether it succeeded or not).

Normal method:

public bool IsValidTimeFormat(string input)
{
    TimeSpan dummyOutput;
    return TimeSpan.TryParse(input, out dummyOutput);
}

Extension method (must be in separate non-generic static class):

public static class DateTimeExtensions
{
    public static bool IsValidTimeFormat(this string input)
    {
        TimeSpan dummyOutput;
        return TimeSpan.TryParse(input, out dummyOutput);
    }
}

Calling the methods for the existing string input; (lets imagine it's initialized with some value).

Normal method:

var isValid = IsValidTimeFormat(input);

Extension method:

var isValid = DateTimeExtensions.IsValidTimeFormat(input);

or

var isValid = input.IsValidTimeFormat();


UPDATE: .NET Framework 4.7

Since the release of .NET Framework 4.7, it can be written a little bit cleaner because output parameters can now be declared within a method call. Method calls remain the same as before.

Normal method:

public bool IsValidTimeFormat(string input)
{
    return TimeSpan.TryParse(input, out var dummyOutput);
}

Extension method (must be in separate non-generic static class):

public static class DateTimeExtensions
{
    public static bool IsValidTimeFormat(this string input)
    {
        return TimeSpan.TryParse(input, out var dummyOutput);
    }
}


Answered By - msmolcic
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 20, 2022

[FIXED] how to convert time saved as int in mysql

 July 20, 2022     integer, mysql, time     No comments   

Issue

I have a column time in a table which is saved as an int in a 24hours format. Example : 1900 (meaning 7:00pm) or 1000(10:00 am) or 930 (9:30 am) What's the simplest way for me to convert it to time to be able to compare it with now()?


Solution

SELECT CAST(`time`*100 AS TIME) FROM table

or

SELECT TIME_FORMAT(`time`*100, '%h:%i %p') FROM table

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f2f08682a6f8cf8410390b8998f7a800



Answered By - Akina
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 12, 2022

[FIXED] How to add custom extension(time) to <message> tag?

 July 12, 2022     android, message, time, xmpp     No comments   

Issue

I'm trying to add time extension to message with custom packet extension. It seems like time gets added while sending message. But at receiver end, it shows null.

This is my packet extension class and EmbeddedExtensionProvider

public class TimestampExtension implements PacketExtension {

    public static final String ELEMENT = "timestamp";
    public static final String NAMESPACE = "urn:xmpp:timestamp";

    public String TIME = null;

    public TimestampExtension() {

    }

    public void setTime() {
        SimpleDateFormat time = new SimpleDateFormat("hh:mm a");
        Date dateTime = new Date();
        String strTime = time.format(dateTime);
        this.TIME = strTime;
    }

    public String getTime() {
        return TIME;
    }

    @Override
    public String getElementName() {
        return ELEMENT;
    }

    @Override
    public String getNamespace() {
        return NAMESPACE;
    }

    @Override
    public String toXML() {
        return "<" + ELEMENT + " xmlns='" + NAMESPACE + "'><time>" + TIME
            + "</time></" + ELEMENT + ">";
    }

    public static class Provider extends EmbeddedExtensionProvider {

        @Override
        protected PacketExtension createReturnExtension(String arg0,
            String arg1, Map<String, String> arg2,
            List<? extends PacketExtension> arg3) {

            return new TimestampExtension();
        }
    }
}

Registering provider

ProviderManager.getInstance().addExtensionProvider(
            TimestampExtension.ELEMENT, TimestampExtension.NAMESPACE,
            new TimestampExtension.Provider());

Sending message with extension

TimestampExtension timeExt = new TimestampExtension();
timeExt.setTime();
msg.addExtension(timeExt);
connection.sendPacket(msg);

Message xml output at sender:

<message id="m55K5-7" to="testfirzan@sushant" type="chat">
<body>hi</body><request xmlns='urn:xmpp:receipts'/>
<timestamp xmlns='urn:xmpp:timestamp'>
<time>01:04 PM</time>
</timestamp>

Message xml output at receiver:

<message id="m55K5-7" to="testfirzan@sushant" from="testsushant@sushant/Smack" type="chat">
<body>hi</body><request xmlns='urn:xmpp:receipts'/>
<timestamp xmlns='urn:xmpp:timestamp'>
<time>null</time>
</timestamp>

It's supposed to show sending time in time element. What i'm doing wrong ?


Solution

Sorry folks for late answer.

Since time was mandatory parameter for me, i end up using DefaultPacketExtension

//To sent message
private void sendMessage(String message, String recipient) {

    Message msg = new Message(recipient, Message.Type.chat);
    msg.setBody(message);

    //Getting current timestamp in string format
    String messageTimeStamp = String.valueOf(System.currentTimeMillis());

    //Creating default packet extension with name as 'timestamp' and urn as 'urn:xmpp:timestamp'
    DefaultPacketExtension extTimeStamp = new DefaultPacketExtension(
                                        "timestamp", "urn:xmpp:timestamp");

    //Setting value in extension
    extTimeStamp.setValue("timestamp", messageTimestamp);

    //Add extension to message tag
    msg.addExtension(extTimeStamp);

    //Send message
    xmppConnection.sendPacket(message);
}


//To receive and parse message with extension implement PacketListener
@Override
public void processPacket(Packet packet) {

    Message message = (Message) packet;

    //Get the extension from message
    DefaultPacketExtension extTimestamp = (DefaultPacketExtension) message
                    .getExtension("urn:xmpp:timestamp");

    //Get the value from extension
    long timestamp = Long.parseLong(extTimestamp.getValue("timestamp"));

    System.out.println("Message :" + message.getBody() + " Timestamp: "+timestamp);
}


Answered By - Sushant
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] How to correct Ref-time in nc file?

 July 10, 2022     cdo-climate, python, r, reference, time     No comments   

Issue

As it is shown in this image , my data starts from 1980-01-01 00:00:00. I would like my ref time to be the first time entry i.e. 1980-01-01. But instead the ref time is 1900-01-01 00:00:00. As the calendar is gregorian, i tried to change the calendar to standard format by using these two different commands and both works

ncatted -a calendar,time,o,c,standard in.nc out.nc

or

cdo setcalendar,standard in.nc out.nc

It changes the calendar:gregorian to calendar:standard but ref time is still 1900:01:01 as shown in the pic 2 enter image description here Need help in this regard. I am using cdo, R, and python. How can I correct the ref time ?


Solution

you can set the reference time with

cdo setreftime,date in.nc out.nc

See this link for details in the online manual

Just to lastly mention that the reftime should be arbitrary for most purposes. Usually one only needs to change the ref time if it is specified by a data protocol (i.e. you want to upload model output to a model intercomparison project and they specify that they want a specific reftime) - the fact that the reftime is not the first timeslice's date is usually not an issue, the dates will still be correct.



Answered By - Adrian Tompkins
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] CakePHP 3.6: Object of class Cake\I18n\FrozenTime could not be converted to int

 March 11, 2022     cakephp, php, time     No comments   

Issue

I am trying to check if a date is later than a week ago in index.ctp:

(((!isset($task->date_end) || is_null($task->date_end))? 
        strotime('now') : $task->date_end) > strtotime('-1 week'))

But I receive this error:

Object of class Cake\I18n\FrozenTime could not be converted to int

To check if there is anything wrong with the dates in the database I changed them all to : 2019-01-02 05:06:00.000000


Solution

When you compare a non-integer to an integer, PHP's type juggling will try to convert the former to an integer, and FrozenTime objects cannot be converted to integers.

You can avoid this fragile construct by using date objects all the way, and use the comparison methods provided by them, for example.

$result = true;
if ($task->date_end !== null) {
    $lastWeek = \Cake\I18n\Time::now()->subWeek(1);
    $result = $task->date_end->gt($lastWeek);
}

See also

  • PHP Manual > Language Reference > Types > Type Juggling
  • Cookbook > Date & Time
  • Cookbook > Chronos


Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, March 10, 2022

[FIXED] i18nFormat with CakePHP 3 - Why does YYYY produce a different year than yyyy?

 March 10, 2022     cakephp-3.0, internationalization, php, time     No comments   

Issue

I'm working in CakePHP 3 and I noticed today that this:

    $time = new Time('now');

    $this->set('time', $time->i18nFormat('YYYY')); // echoes '2015'

Echoes 2015. Changing it to lowercase 'yyyy', instead, produces 2014.

    $time = new Time('now');

    $this->set('time', $time->i18nFormat('yyyy')); // echoes '2014'

Why is this the case?


Solution

Uppercase Y is the year that the week of the timestamp is in "Week of Year" based calendars. This week now, is in 2015 so it returns 2015. Lowercase y is the current year for the timestamp, which for now is 2014.

Date Field Symbol Table



Answered By - AbraCadaver
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, March 3, 2022

[FIXED] How do I get the difference of time in human readable format with Laravel 5?

 March 03, 2022     laravel-5, php, time     No comments   

Issue

I want to display the difference between the current date and time with the one stored in the updated_at column. However, I want it to be human-friendly like:

53 mins ago
2 hours ago
3 days ago

Is there a function out there that I could use to make it easier?

To be sure that you understand me, let's say I have a column (updated_at) in my database which is equal to 2015-06-22 20:00:03 and the current time is 20:00:28. Then I'd like to see:

25 mins ago

When it's higher than 59 minutes, I want to show only hours and when it's higher than 24 hours I'd like to see how many days ago.


Solution

By default, Eloquent converts created_at and updated_at columns to instances of Carbon. So if you are fetching the data using Eloquent, then you can do it as below.

$object->updated_at->diffForHumans();

If you want to customize the fields that will be mutated automatically, then within your model, you can customize them as you wish.

// Carbon instance fields
protected $dates = ['created_at', 'updated_at', 'deleted_at'];


Answered By - Burak
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 27, 2022

[FIXED] Cake\I18n\Time object echoes wrong hour plus daylight saving time

 February 27, 2022     cakephp-3.0, dst, internationalization, php, time     No comments   

Issue

I have a CakePHP 3 project with those configurations:

app.php:

    'defaultLocale' => env('APP_DEFAULT_LOCALE', 'pt_BR'),
    'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'America/Sao_Paulo'),

bootstrap.php

date_default_timezone_set('America/Sao_Paulo');

When i

echo date("Y-m-d H:i:s"); it shows right date and time;

But when i

$data = Time::now();

and

echo $data;

It is shown with +1 hour because we used to add one hour for dst but this year it was canceled.

The strange part is when i debug $data it shows right, without +1 hour:

\src\Controller\TesteController.php (line 104)
object(Cake\I18n\Time) {

    'time' => '2019-10-24T15:15:07-03:00',
    'timezone' => 'America/Sao_Paulo',
    'fixedNowTime' => false

}

echo data:24/10/2019 16:15:07`

I've tried to add Time Zone with

$dateTimeZoneBrasil = new \DateTimeZone("America/Sao_Paulo");

and

$data = Time::now($dateTimeZoneBrasil);

But still shows with +1 hour.

UPDATE

Here are the tests to reproduce the problem:

ini_set('intl.default_locale', 'pt_BR');
I18n::locale('pt_BR');
date_default_timezone_set('America/Sao_Paulo');
Time::setToStringFormat([\IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT]);
$time = Time::now();
debug($time);
debug((string)$time);
debug($time->i18nFormat());
debug($time->i18nFormat('yyyy-MM-dd HH:mm:ss'));
debug($time->format('Y-m-d H:i:s'));
debug($time->getTimezone()->getTransitions(strtotime('2019-01-01'), strtotime('2020-01-01')));
phpinfo(INFO_MODULES);

And my results:

\src\Controller\TesteController.php (line 79)
object(Cake\I18n\Time) {

    'time' => '2019-10-25T09:34:37-03:00',
    'timezone' => 'America/Sao_Paulo',
    'fixedNowTime' => false

}
\src\Controller\TesteController.php (line 80)
'25/10/19 10:34'
\src\Controller\TesteController.php (line 81)
'25/10/19 10:34'
\src\Controller\TesteController.php (line 82)
'2019-10-25 10:34:37'
\src\Controller\TesteController.php (line 83)
'2019-10-25 09:34:37'
\src\Controller\TesteController.php (line 84)
[
    (int) 0 => [
        'ts' => (int) 1546308000,
        'time' => '2019-01-01T02:00:00+0000',
        'offset' => (int) -7200,
        'isdst' => true,
        'abbr' => '-02'
    ],
    (int) 1 => [
        'ts' => (int) 1550368800,
        'time' => '2019-02-17T02:00:00+0000',
        'offset' => (int) -10800,
        'isdst' => false,
        'abbr' => '-03'
    ],
    (int) 2 => [
        'ts' => (int) 1572750000,
        'time' => '2019-11-03T03:00:00+0000',
        'offset' => (int) -7200,
        'isdst' => true,
        'abbr' => '-02'
    ]
]

Modules:

date
date/time support   enabled
"Olson" Timezone Database Version   2018.7
Timezone Database   external
Default timezone    America/Sao_Paulo
Directive   Local Value Master Value
date.default_latitude   31.7667 31.7667
date.default_longitude  35.2333 35.2333
date.sunrise_zenith 90.583333   90.583333
date.sunset_zenith  90.583333   90.583333
date.timezone   America/Sao_Paulo   America/Sao_Paulo

Solution

The problem is in the operating system where the application is running. The time zone rules to DST are out of date. Brazil has changed its daylight saving time rules recently. But other governments can do this at any time as well.

The IANA organization maintains an up-to-date bank with time zones and other characteristics. The latest version is 2019c, published at 2019-09-11 [1].

The CAKEPHP Framework uses the PHP INTL library. The PHP INTL library uses ICU library which is part of the Linux distribution packages [2]. And ICU library uses the IANA data.

So, an outdated version of ICU will affect how PHP handles dates.

You can check the ICU version on phpinfo() or using the command:

php -i | grep ICU

The latest version of the ICU library is 65.1 and was published on 2019-10-03 [3] and doesn't include IANA version 2019c. However, you can see that in the ICU repository they have already updated the zoneinfo64.txt file for future releases [4].

The latest version of ICU on CentOS 8 is 60.5 [5]. If you are in the Amazon AMI distribution (EC2, EBS, RDS) it will be even worse as the latest version (2018-05-14) of ICU for their distribution is 50.1.2 [6]. The latter has a release date at 2012-12-17 [7]

If you are an expert in download and compile Linux services, you can compile the ICU package using the latest source code.

If you can accept an outline solution, you can lie temporarily using the America/Fortaleza time zone instead of America/Sao_Paulo. Fortaleza zone hasn't belonged to daylight saving time since 2012.



Answered By - William
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 17, 2022

[FIXED] CakePHP find condition for a query between two dates

 February 17, 2022     between, cakephp, date, time     No comments   

Issue

I have a start and an end date in my database and a $date variable from a form field. I am now trying to query all the rows where $date is either = start/end date in the db, or ANY date between those two.

It's kind of the opposite of what is described in the docs of how daysAsSql works. I can't figure out how to get it to work. The following line does not work as a find condition in the controller:

'? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),

Any help is greatly appreciated. This is driving me crazy.

Here is the complete Query and corresponding SQL:

$conditions = array(
            'conditions' => array(
            'and' => array(
                '? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),
                'Item.title LIKE' => "%$title%",
                'Item.status_id =' => '1'
                )));

        $this->set('items', $this->Item->find('all', $conditions));



WHERE (('2012-10-06' BETWEEN 'Item.date_start' AND 'Item.date_end') AND (`Item`.`title` LIKE '%%') AND (`Item`.`status_id` = 1))

Solution

$conditions = array(
        'conditions' => array(
        'and' => array(
                        array('Item.date_start <= ' => $date,
                              'Item.date_end >= ' => $date
                             ),
            'Item.title LIKE' => "%$title%",
            'Item.status_id =' => '1'
            )));

Try the above code and ask if it not worked for you.

Edit: As per @Aryan request, if we have to find users registered between 1 month:

$start_date = '2013-05-26'; //should be in YYYY-MM-DD format
$this->User->find('all', array('conditions' => array('User.reg_date BETWEEN '.$start_date.' AND DATE_ADD('.$start_date.', INTERVAL 30 DAY)')));


Answered By - Arun Jain
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 13, 2022

[FIXED] CakePHP 3 - Comparing and modifying dates

 February 13, 2022     cakephp, cakephp-3.0, date, time     No comments   

Issue

In the CakePHP 3 Cookbook on Date/Time, you can compare time intervals with future/past days/weeks using IsWithinNext/WasWithinNext. You can also modify dates/times by doing a ->modify('extra time') - eg. if $date = 2016-01-01, $date->modify('+1 week') would mean $date = 2016-01-08.

These features require the use of Cake\i18n\Time. However, when I attempted to use these features, I received a Cake error:

Call to a member function isWithinNext() on string.

This is the code I used:

$date_start = \Cake\Database\Type::build('date')->marshal($data['session']['date_start'])->i18nFormat(); //before hand my dates were in the form of an array comprised of Year, Month and Day. This changes them into date format.
if($date_start->isWithinNext('1 week')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+48 hours');
} elseif ($date_start->isWithinNext('2 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} elseif ($date_start->isWithinNext('3 weeks')){
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+1 week');
} else {
    $deposit_due = $booking->date_confirm;
    $deposit_due->modify('+2 weeks');
}

Solution

Calling i18nFormat() returns a formatted string as you can look up in the API: https://api.cakephp.org/3.4/class-Cake.I18n.DateFormatTrait.html#_i18nFormat

This, for example, should work:

$date_start = new \Cake\I18n\Time($data['session']['date_start']);
debug($date_start->isWithinNext('2 weeks'));


Answered By - Marijan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] JavaScript JSON response - formatting dates and times

 February 13, 2022     cakephp-3.0, date, javascript, json, time     No comments   

Issue

When I trigger my JavaScript code to open up a modal, an AJAX call is sent to retrieve data in JSON format. I then use the JSON response to populate my modal.

The link that triggers the JavaScript is this:

<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>

This is an action from a table on a CakePHP 3 View. $session->id is decided based on which row of data the link is clicked. Popup is an empty CakePHP 3 function that just facilitates the JavaScript working and the modal opening up.

The JavaScript which triggers the modal is as follows:

<script type="text/javascript">
    $(function () {
        $('.view').click(function (ev) {
            ev.preventDefault();
            var sessionId = $(this).attr('data-id');
            $('#viewModal').modal('show');
            $.ajax({
                url:"localhost/project/sessions/details/"+sessionId+".json",
                type:'POST',
                success:function(res) {
                    if(res) {
                        document.getElementById("prdatestart").innerHTML = res.date_start;
                        document.getElementById("prstarttime").innerHTML = res.starttime;
                    }
                }
            });
        });
    });
</script>

The details function from my CakePHP 3 SessionsController is this, which retrieves the relevant data for the $session->id that was obtained earlier:

public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }

This is my modal in full that then opens up:

<!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="modal-title" id="viewModalLabel">Session Details</h3>
                <br>
                <table class="vertical table col-sm-2">
                    <tr>
                        <th>Starting Date:</th>
                        <td id="prdatestart"></td>
                    </tr>
                    <tr">
                        <th>Starting Time:</th>
                        <td id="prstarttime"></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>
            </div>
        </div>
    </div>
</div>

However, my dates and times are in this format:

  • Date: 2017-05-12T00:00:00+00:00
  • Time: 2017-03-31T00:14:00+11:00

For the date response, I only need the date, and formatted in D/M/Y format. For the time response, I only need the time, formatted in 12 hour hh:mm AM/PM format. (I don't need the timezone stuff at the end as that was taken into account when the data was first submitted).


Solution

simply use with normal javascript new Date() .post like simple js function cal(yourdatevarible ,whichtype) type=date|time

var date = '2017-05-12T00:00:00+00:00';
var time = '2017-03-31T00:14:00+11:00';

console.log(cal(date, 'date'))
console.log(cal(time, 'time'))

function cal(date, type) {

  var m = ['Jan', 'Feb', 'Mar', 'Aprl', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  //var w =['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var x = new Date(date)
  var h = x.getHours() > 12 ? x.getHours() - 12 : x.getHours();
  var format = x.getHours() > 12 ? 'PM' : 'AM';
  if (type == 'date') {
    return x.getDate() + ' ' + m[x.getMonth()] + ' ' + x.getFullYear();
  } else {
    var min = x.getMinutes().toString().length > 1 ? x.getMinutes() : '0' + x.getMinutes();
     h =h.toString().length > 1 ? h : '0' + h;
    return h + ':' + min + ' ' + format;
  }
}



Answered By - prasanth
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 7, 2022

[FIXED] Advice: I'm trying to make a tracking time feature in my application but when should I send the data to the backend

 February 07, 2022     api, laravel, reactjs, time     No comments   

Issue

I'm making a client management system in Laravel and ReactJS. I use Laravel for the backend and the api and ReactJS (with Context API) for the frontend of course.

I want to add a tracking timer into my application so the idea is that you can click on a button and select a client and it will start a timer, when you click on the stop button it will stop the timer and the time passed, is how much you spend working for that client.

My question is when should I send the time spend to the backend API?

My ideas:

  1. After the users clicked on the stop button.
  2. Every single minute (but with this technique the client will send a lot of requests to the backend).

NOTE: When a user refreshes the page the timer needs to continue where it left off.

Does anyone have some advice on how to do this?


Solution

From your requirement, I guess that's fair enough when the stop button is clicked. In fact, you may capture the date-time

  • once start is clicked
  • once again when the stop button is clicked also find the difference between these two to identify the time consumed in your client application.

This way, refreshing the page will have no impact since these are loosely coupled.



Answered By - Harry
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing