Epoch to date UTC+3 - javascript

I used this code to convert epoch to human readable date
var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
I need to change it to UTC+3 how can i do this ?
Thanks for your help

The Date constructor treats time values as UTC. Date objects only ever represent UTC time, the "local" values produced by toString methods use system settings to determine the offset to use, but that's only for the sake of producing a timestamp, it doesn't change the underlying Date or its time value.
If you want a specific offset, you can choose an appropriate IANA location such as Africa/Nairobi, which is +3 all year round, and produce a timestamp using toLocaleString or Intl.DateTimeFormat, e.g.
console.log(
new Date().toLocaleString('default',{timeZone:'Africa/Nairobi', timeZoneName:'short'})
);

Just curious - but couldn't you just append 3 hours onto your timestamp before formatting it with your existing code. I'm curious if there's some date/calendar subtlety where this wouldn't reliably work.
const THREE_HOURS_IN_MS = 3*60*60*1000;
var date = new Date(timestamp*1000 + THREE_HOURS_IN_MS);
// rest of your code stays unchanged
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

You can use moment.js utcOffset to achieve this easily:
const moment = require("moment");
const timestamp = 1619071948 * 1000;
console.log(moment(timestamp).utcOffset(180).format("YYYY-MM-DDThh:mm:ssZ"));
The offset provided is in minutes
https://momentjs.com/docs/#/manipulating/utc-offset/

Related

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Javascript: formatting a date [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I want to the current date/time formatted in this format:
year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var milli = now.getMilliseconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
if(milli.toString().length == 1) {
var milli = '0'+milli;
}
var m_session_startTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Leverage template literals instead of concatenation and padStart() to fill leading zeros.
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");
const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
You could use moment.js, it really helps you with formatting dates.
console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.
You can then format the date according to your need,
YYYY is the full year (2018)
MMMM is the full month name (July)
(you can also use MMM for the short version of the month name)
DD is the day as a number (24)
(you can also use dddd for the full name of the day or ddd for the short name)
h is the hour as number (22)
mm is the minute as a number (23)
ss is the second as a number (as an example 22)
SSS is the millisecond as a number (example 245)
Try this?
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
console.log(jsonDate);
> 2018-07-24 20:32:06:435
Alternatively, if you want to split the entire thing into substrings:
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];
console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));
> 2018-07-24 21:03:05:706
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706
As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.
Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.
var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
https://momentjs.com/

hours and minutest to timestamp - Javascript

I have hours and minutes in firebase format (can't change this): 2230
I need to convert this to normal date, year, day and month are current time, only hour and minutes are specifed
var startDate = new Date();
I need to set date something like this:
startDate.setHours(myhours, myminutes, myday, 0);
An easy way to do this is to create a new Date, then just update those values:
const hours = 15; // 24-hour format, 0 = midnight, 15 = 3PM
const minutes = 45;
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
This will give you a Date object with the current time (as defined by the client's computer), but with the hours and minutes set to what you specify, and seconds set to 0 (since having 15:45:58 is weird).
To convert the string to variables, just do this:
const [, hours, minutes] = '2230'.match(/(\d{2})(\d{2})/).map(m => parseInt(m));
console.log(hours, minutes);
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
Keep in mind that it will assume you are setting it based on GMT (timezone offset +0000). If you want it relative to your time, either change the date object (if you just need its values to match) or shift it by your timezone offset.
const hour = 15;
const minute = 45;
const d = new Date();
d.setHours(hour - (d.getTimezoneOffset() / 60)); // adjust hour to local timezone
d.setMinutes(minute);
d.setSeconds(0);
console.log(d);

How to convert 7:30 AM time to javascript Date type?

How can I convert time taken from form in html in the format of Hours:Minutes AM/PM to Date class object in javascript.
You could use regex to parse the time and set it to a date object.
var d = new Date(),
s ='7:30 AM',
parts = s.match(/(\d+)\:(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours, minutes,0,0); // As suggested by #RobG
// d.setHours(hours);
// d.setMinutes(minutes);
console.log(d);
Let's assume you have your input in the form var time = "7:30 AM".
The first thing we want to do is get the AM/PM out of the way.
time.split(' ') gives us ["7:30", "AM"], so we do:
var timePeriod = time.split(' ')[1];
time = time.split(' ')[0];
See MDN's article on .split if you have any questions
We now have timePeriod === 'AM' and time === '7:30'.
We can use the same trick to get hour and minute.
var hour = time.split(':')[0];
var minute = time.split(':')[1];
It would be easier to just use numbers, so we'll normalize our data a bit here.
if (timePeriod === 'AM') {
// Do not use `hour += 12` here as that will not convert the result to a number
hour = 12 + hour
}
And now we just have numbers to work with. Let's start with the current date:
var currentDate = new Date();
and modify the hour and minute to match the data we just parsed:
currentDate.setHours(hour);
currentDate.setMinutes(minute);
Now we should have a date that we can work with!
*See MDN's article on the Date object if you have any questions******

how to get current time and then compare them using jquery

this is my code:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
alert(minutes+"/"+hours+"/"+month + "/" + day + "/" + year)
but , i think it hard to compare with two time ,
what can i do ?
thanks
If you really want to know whether two Date objects represent precisely the same time, or are before/after one another, it's quite easy: just compare the two Dates via the getTime() method, which returns an integer timestamp for the object. For example,
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
would return true if myDate is before 'now', false if it is now or in the future.

Categories