get UTC timestamp from formated date - javascript - javascript

I have a UTC date string -> 10/30/2014 10:37:54 AM
How do I get the timestamp for this UTC date? As far as I know, following is handling this as my local time
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime();
Thank you

You can use Date.UTC to create a UTC format date object.
Reference:
Stackoverflow
MDN
(function() {
var d = new Date();
var d1 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()));
console.log(+d);
console.log(+d1);
})()

You can decrease the "TimezoneOffset"
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime() - (d.getTimezoneOffset() *1000 * 60);
Also u can use the UTC function
var d = new Date("10/30/2014 10:37:54 AM");
return Date.UTC(d.getFullYear(),d.getMonth()+1,d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds());

If the format is fixed, you could easly parse it and use the Date.UTC() API.

A quick hack would be to append UTC to the end of your string before parsing:
var d = new Date("10/30/2014 10:37:54 AM UTC");
But I would advise you to use a library like moment.js, it makes parsing dates much easier

Try Date.parse
var d = new Date("10/30/2014 10:37:54 AM");
var timstamp = Date.parse(d) / 1000;

Hope this helps:
Date date= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
date = sdf.parse(date.toString());
String timestamp = sdf2.format(date);

Related

how to get UTC time in yyyyMMdd’T’HHmmss’Z’ fromat in javascript

I have tried this below
var dt = new Date();
utc = dt.toISOString();
console.log(utc)
which gives the result as such 2021-04-22T04:32:33.676Z
but I want this UTC DateTime in exactly yyyyMMdd’T’HHmmss’Z format...
As per my understanding, you don't want those extra dashes coming in the date string. You can simply remove them using replaceAll as below.
var dt = new Date();
utc = dt.toISOString().replaceAll('-', '');
The output will be 20210422T04:45:28.739Z
You can use moment.js library which allows string format to specify. It also supports lot more operations on dates.
var dt = moment();
console.log(dt.utc().format("YYYYMMDD[T]HHmmss[Z]"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
With your explanation, I think you want the date and time to be properly displayed in utc format right?
I think using toLocaleString() method will give you what you want.
var dt = new Date();
utc = dt.toLocaleString();
One approach using plain javascript would be
var dt = new Date();
function format(num) {
return num < 10 ? "0" + num : num;
}
console.log("" + dt.getUTCFullYear() + format(dt.getUTCMonth()) + format(dt.getUTCDate()) + "T" + format(dt.getUTCHours()) + format(dt.getUTCMinutes()) + format(dt.getUTCSeconds()) + "Z")
var dt = new Date();
dt.setMilliseconds(0);
utc = dt.toISOString().replace(/[-,.,:]/g,"").replace(/000Z/, "Z");
console.log(utc)

Get Seconds from midnight UTC

I simply need the number of seconds from the midnight of the present day.
It's a labyrinth of JS Date methods I can't untangle from.
I already searched for an off-the-shelf snippet. I tried this but it returns local time, not UTC:
let date = new Date(),
d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(),
date.getUTCSeconds())),
e = new Date(d),
secsSinceMidnight = Math.floor((e - d.setUTCHours(0,0,0,0)) / 1000);
I think you had the right idea, but got lost in the implementation. Your assignment to d is just a very long winded way of creating a copy of date that is equivalent to the assignment to e.
To get "seconds from UTC midnight", create a Date for now and subtract it from a copy that has the UTC hours set to 00:00:00.000.
function secsSinceUTCMidnight() {
var d = new Date();
var c = new Date(+d);
return (d - c.setUTCHours(0,0,0,0)) / 1000;
}
console.log('Seconds since UTC midnight: ' +
secsSinceUTCMidnight().toLocaleString() + '\n' + new Date().toISOString());

Convert UTC to local time Javascript

I'm trying to convert UTC time to local time, but the below code is not working. What's wrong in it?
var parsedStartDateTime =
new Date(moment.unix(parseInt(data['StartDateTime'].substr(6)) / 1000));
var startDateTimeMoment =
moment.tz(parsedStartDateTime, tzName);
var formatted_date =
startDateTimeMoment.format("MMM DD YYYY h:mm:ss A");
To format your date try this:
var d = new Date();
var formatD = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
Reference: Javascript to convert UTC to local time
Try appending UTC to the string before converting it to a date then use toString() method of date.
Example:
var myDate = new Date('7/1/2014 5:22:55 PM UTC');
date.toString(); //this should give you local date and time
This code was taken from here
Here is my solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
date.toLocaleString().replace(/GMT.*/g,"");

JS - How to get and calculate the current date

Sorry, but what is the fastest way to display the current date?
2014-01-18 Saturday 12:30
with this function or how do it the right way?
var d=new Date();
var t=d.getTime();
Try
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth()+1; //January is 0!
var yy = d.getFullYear();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var day=weekday[d.getDay()];
var h = d.getHours();
var m = d.getMinutes();
alert(yy+"-"+mm+"-"+dd+" "+day+" "+h+":"+m)
DEMO
var d = new Date();
alert(d.toString());
If you don't mind the format, you can do it in one line:
''+new Date()
You only need to use a Date object as a string, in order to implicitly call its .toString() method, which
returns a String value. The contents of the String are
implementation-dependent, but are intended to represent the Date in
the current time zone in a convenient, human-readable form.
new Date().toGMTString()
It's something similar to what you are looking for
If you want complicate the output you can get element by element and format yourself the date (or you can use Globalize.js)

Convert Date and Time into a UTC formatted Date - Javascript

I have two variables, date & time...
var date = "2012-12-05";
var time = "18:00";
How can I format this into a UTC formatted date. This is so I can use it within the Facebook API..
Facebook states I need it in this format:
Precise-time (e.g., '2012-07-04T19:00:00-0700'): events that start at a particular point in time, in a specific offset from UTC. This is the way new Facebook events keep track of time, and allows users to view events in different timezones.
Any help would be much appreciated.. Thanks!
This format is called ISO 8601
Do you know what timezone you are in? If you do, you can do like this:
var datetime = date + 'T' + time + ":00+0000';
if the timezone is +0.
if not, then:
var d = new Date()
var n = d.getTimezoneOffset();
var timeZone = Math.floor( Math.abs( n/60 ) );
var timeZoneString = (d.getTimezoneOffset() < 0 ? '-' : '+' ) + ( timeZone < 10 ? '0' + timeZone : timeZone ) + '00';
var datetime = date + 'T' + time + ':00' + timeZoneString;
Here is a fiddle: http://jsfiddle.net/ajySr/
Try the following:
var date = new Date(2012, 12, 5, 18, 0, 0, 0);
var date_utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
The Date function can be used the following ways:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
This was taken from a related post here: How do you convert a JavaScript date to UTC?
To find out more, please refer to: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

Categories