I want to set visitors first visiting time and date of my website as cookie.
I tried the code below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script>
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
Cookies.set('vtime', time, { expires: 7, path: '' });
alert(Cookies.get('vtime'));
</script>
Using the above code the time is changing on reload. Please help me to solve this.
The problem is cookie gets replaced on every refresh. So just check if the cookie is set already
if(!Cookies.get('vtime')) {
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
Cookies.set('vtime', time, { expires: 7, path: '' });
alert(Cookies.get('vtime'));
}