Skip to main content

Display the current date and time in Matlab, Using Built-in Function clock

Problem

Ask the user for the format of the date required, so that the person selects the format according to his/her convenience, and after the user gives the required date format then display the date and time in a neat and clear way so that the user understands the date and time accordingly. For this problem use the most common date formats. Use the built-in function clock in Matlab to accomplish this task.

Solution

Before we solve this problem let us first find the most common date formats so that we can proceed forward. By doing some Google Search and found these as the common types:
1) DD-MM-YYYY
2) MM-DD-YYYY
3) YYYY-MM-DD
4) YYYY-DD-MM
If you feel that there are few more of date formats then please feel free to add them to your script. For now let us stick to the above to solve the problem because solving the problem to know the Matlab concepts is important than any other stuff. To know more about the date formats used in different countries then see: Wikipedia - Date format by country
Now coming back to solving the problem, we will ask the user to select the input format. Then we use the clock built in function in Matlab to get the date and time of the user in his/her local computer.
Then we will use the if else to give the output based on the user input for the date format required.
I suggest you to see the program section first so that you can understand by the program and for detailed explanation refer to the explanation section below the program section. To solve this problem some of the concepts you need to know are as follows:
1) fprintf function in Matlab
2) input function in Matlab
3) clock built function in Matlab
4) vectors in Matlab
5) Variables in Matlab
6) If else and elseif in Matlab
7) Comments in Matlab
8) round function in Matlab

Program


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
%Ask the user for input
fprintf('Choose your time format:\n')
fprintf('1) DD-MM-YYYY\n')
fprintf('2) MM-DD-YYYY\n')
fprintf('3) YYYY-MM-DD\n')
fprintf('4) YYYY-DD-MM\n')
user_input = input('');
%using the built-in function clock to get date and time
time = clock;

%Divide correspondingly
year = time(1);
month = time(2);
day = time(3);
hours = time(4);
minutes = time(5);
seconds = time(6);
seconds = round(seconds);

if user_input == 1
    fprintf('Date: %d-%d-%d\n',day,month,year)
    fprintf('Time: %d:%d:%d\n',hours,minutes,seconds)
elseif user_input == 2
    fprintf('Date: %d-%d-%d\n',month,day,year)
    fprintf('Time: %d:%d:%d\n',hours,minutes,seconds)
elseif user_input == 3
    fprintf('Date: %d-%d-%d\n',year,month,day)
    fprintf('Time: %d:%d:%d\n',hours,minutes,seconds)
elseif user_input == 4
    fprintf('Date: %d-%d-%d\n',year,day,month)
    fprintf('Time: %d:%d:%d\n',hours,minutes,seconds)
else
    fprintf('You have not entered the input correctly!!\n')
    fprintf('The program will restart automatically.\n\n')
    fprintf('-------------------RESTART - DATETIME--------------\n\n')
    datetime
end

I have saved this file as datetime.m on my local computer.
Check out the explanation section why I am asking the user to give the input before computing the date and time data.

Explanation

First line is a comment.
From lines 2-6 we have written a simple plain fprintf statements to display the available date formats with us so that the user can select from the options.
In line number 7 we have added an input function so that the user can give the input of his choice.
Line 8 is again a comment for the programmers to understand the further program
Line 9 we have used the clock function and stored the value in a variable time. Clock function gives the output of the current date and time in a neat vector fashion. The format in which it gives output is as follows:Click on the links if you don't know what they are in the real world or want to know more about them scientifically.
1) Year
2) Month
3) Day of the Month
4) Hour
All the above are integers except the seconds which is in double to give the accurate output of milliseconds after the decimal.
From Line 12 to 17, as we know the sequence of output we will store each element in the vector to store in the corresponding variables so that we can use it further.
In Line 18 we are rounding the decimal or double value of the seconds which consists of both seconds and milliseconds for few reasons - Firstly the user will not care about the milliseconds because they only need accuracy till seconds, Secondly after the user has given the input, the program below the line 7 will start executing and lets say it takes some time. So I have rounded off the seconds to compensate that time. Even though we cannot say that it takes the milliseconds value of the real time to execute the program but for the sake of simplicity I have done so.
In line 20 I have started the if statement to check the user input. If the user has given the input of 1 then the fprintf functions in the lines 21 and 22 will execute and will display the date and time to the user in a neat and good fashion. 
In the similar way the lines 23-31 will get executed using the elseif of matlab and will display the date and time according to the user input.
Finally let us say if the user gives an input of 5 then our program doesn't have any if or else if to handle the user_input of 5 so we are using the else of the matlab to warn the user that he/she has selected a wrong input and the fprintf functions in the lines 33, 34 and 35 gets executed. After the execution of the line 35 again we are calling our script datetime inside the script to start the execution of our script again.
Okay we have seen above that we are rounding off seconds to get an approximate value, but why don't we simply compute the whole data of date and time and then ask the user to give the input so that as the user gives the input the date and time is same as when pressing the return key or enter key on keyboard. But remember that the clock function has its values changing every second but as we are storing the value in a variable time, the value of time at the time of execution of the clock statement gets stored. Now we are asking the user to give the input and the user has to read the different types of date formats and he has to select one and give the input and this will take at least a few seconds of time, or lets say if the user got a phone call and left the computer to attend the phone call then the error in the output will be the time duration of the phone call. So to avoid this we are asking the user input first and then as soon as he/she gives the input the data is computed just giving an error of few milliseconds which is negligible instead of having an error of seconds or even hours( :-) ).

Input/Output

Display date and time in Matlab using the clock function
Display date and time in Matlab using the clock function

Try it yourself

Write the same program such that the user can have more options to choose and comment your program and output in the comment box below. Google to get more types of date formats.

Final Note

I have tried to explain everything in this post in such a way that it is easy to understand, but if you have not understood anything or have a doubt then please do contact me. You can contact me from here: Contact me.
The above code was high lighted using hilite.me
Keywords: datetime, Matlab, clock function, display, round function, date formats

Popular posts from this blog

Problem 60 Project Euler Solution with python

Prime pair sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. This problem is j u st a brute force problem. If you have come here because you don't know the limit upto which you will h ave to gener ate the prime numbers t hen go ahe ad and t r y with 10,000 . When I first start ed solving the problem I chose 1 million(beca use most of the problem s on project E uler have this limit ), but it took very long for the computer to fin d the solution. After searching on the internet then I found many people choosing 10, 000 so I have changed my in put f rom 1 million to 10000 and the output was f ast. He...

Add/Embed SVG to Blogger website

In this post I will tell you my method(trick) of adding SVG images in a blogger website or blog. Before starting , the first thin g I am assu m ing is that you are aware of SVG if you are here. If not please see S calable V ec tor G raphics Recently when I tried to embed a SVG image for a post on pygal, I tried uploading the SVG file and blogger Image uploader came up with an error, because of which I had to find some other way.  SVG File upload Error in Blogger  I started sea rc hing Google " Embed SVG in Blogger " . I found blogorrhea , w h ich gave some i nformatio n on add ing SVG directly as a markup , which worked , but I faced another problem using this . Also th is guy has used lot of Javascript which was confusin g for me, being new to using SVG.   So I first t houg ht of learning on h ow to embed SVG in HTML and t his on e worked out. Actually we can embed SVG in HTML i n following ways: Using Object tag Using Iframe tag Using embed...

Making a quiz web app with python and flask

Edit : When you are creating a web app with h tml templates, then y ou will have to sa ve the html file in templates folder in the Current Wor ki ng Directory( CWD). If you save the file in the C W D directl y you will get a TemplateNotFound error. Thank you Udhay for pointing it out.   In this post we will create a quiz website using python . I will be using the flask framework . After reading this tutorial you will learn form submission , flask templates , python code in flask templates , shuffling the questions and options with the random module and few others.  Please note that this tutorial is not big as it seems to be. Some of the code has been rewritten to maintain consistency and also font size is somewhat big so that your eyes won't get stressed reading this tutorial. Also the content has not occupied the full width of the page. In this tutorial I am assuming that you are having a very basic understanding of the flask framework . Please refer the documenta...