getTime method is not working in javascript [duplicate] - javascript

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
Closed 1 year ago.
I have a little javascript file which I need to get the time of different timezone. I am only able to get the date but not the time.
let today = new Date();
let time = today.getTime();
let us = new Intl.DateTimeFormat('en-US').format(time);
let sv = new Intl.DateTimeFormat('sv').format(time);
console.log(us)
console.log(sv)
result in the console
2/25/2021
2021-02-25

i was able to solve the problem by using a javascript method called split whic was able to get me only the time part of the result.
const str3 = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
ch_time = str3.split(" ")[1];
console.log(ch_time)

You can specify the date and time format using the "timeStyle" and "dateStyle" options. These can be full, long, medium, and short.
let us = Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(time));
The above code will produce:
"Weekday, day Month Year at hh:mm:ss GMT+X"

Related

How to get last 2 digits of year from Javascript date [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
How to get 2 digit year w/ Javascript? [duplicate]
(5 answers)
Closed 3 years ago.
I have string in the following format "30.11.2019". I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19".
The following code doesn't work
var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear();
new Date() does not work with a single string argument in that format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Easiest way is to call it with 3 arguments (year, month, day).
Do note that month is the month index (0 based), so November (11th month) is actually 10th in the format that Date expects.
new Date(2019, 10, 30).getFullYear() % 100;
// returns 19;
If you can't do it this way and you simply must work around the string format mentioned, then you can just do
const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);
I'm not entirely sure if you want only short representation of the year or whole date, BUT with short representation of the year on it - if so, then I would suggest using toLocaleDateString method:
new Date(2019, 10, 30).toLocaleDateString('pl', {day: 'numeric', month: 'numeric', year: '2-digit'})
It will return you:
"30.11.19"
or if you want to get the short year date only:
new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})
it will return you:
"19"
You can get last two digits with the following code:
var strDate = new Date(); // By default Date empty constructor give you Date.now
var shortYear = strDate.getFullYear();
// Add this line
var twoDigitYear = shortYear.toString().substr(-2);
Since the string you're using isn't in a format recognized by Date.parse() (more on that here), you need to manually create that Date object.
For example:
const strDate = '30.11.2019';
let [d,m,y] = strDate.split(/\D/);
const date = new Date(y, --m, d);
console.log(date.getFullYear())
You can then use Date.getFullYear() to get the year and extract the last two digits, as you need.
do not need split string, I think.
using moment
yarn add moment
const moment = require( 'moment' );
const simpleYear = moment( "30.11.2019", "DD.MM.YYYY" ).format( "YY" );
console.log( "simpleYear = " + simpleYear );
var strDate = "30.11.2019";
var lastdigit = strDate.slice(-2);

getMonth() in Javascript from format dd/mm/yyyy [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)

Get millis when using new Date().toLocaleTimeString() [duplicate]

This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
Closed 4 years ago.
I have this code:
v.d = new Date().toLocaleTimeString();
it yields something like this:
20:11:40
So this is the time of day to the second, without milliseconds.
My question is: is there a built in call that can show just the time with milliseconds?
I am looking for something like this (to the millisecond):
20:11:40.124
This works, but I am looking for something more compact if possible:
const d = new Date();
v.d = d.toLocaleTimeString() + `.${d.getMilliseconds()}`;
this yields:
20:17:30.744
note that to make this work well, you need to add this part:
Formatting milliseconds to always 3 digits for d.getMilliseconds() call
There’s to ISOString(). But stepping back a level, with that exception there’s no standard for formatting dates in js. So you can use toISOString or build up your own string with individual date functions.
I did find one issue with your original solution. When I perform it it yields hh:mm:ss PM.mil. I assume you want hh:mm:ss.mil Here is that solution written as a function so you can pass the date object in and get the proper format:
const d = new Date()
const getTimeWithMilliseconds = date => {
const t = d.toLocaleTimeString();
return `${t.substring(0,8)}.${date.getMilliseconds() + t.substring(8,11)}`;
}
console.log(getTimeWithMilliseconds(d));
Or if you want it in 24 hour format:
const d = new Date()
const getTimeWithMilliseconds = date => {
return `${date.toLocaleTimeString('it-US')}.${date.getMilliseconds()}`;
}
console.log(getTimeWithMilliseconds(d));
You can't depend on toLocaleTimeString returning a specific format as it's implementation dependent. It's much more reliable to build the format yourself, e.g.:
function getFormattedTime(date) {
var d = date || new Date();
var z = n => ('0'+n).slice(-2);
var zz = n => ('00'+n).slice(-3);
return `${z(d.getHours())}:${z(d.getMinutes())}:${z(d.getSeconds())}.${zz(d.getMilliseconds())}`;
}
console.log(getFormattedTime());
console.log(getFormattedTime(new Date(2018,1,1)));
console.log(getFormattedTime(new Date(2018,4,30,23,51,12,89)));
Also see Where can I find documentation on formatting a date in JavaScript?

Get day from Date in JavaScript [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks

How to create a date object from string in javascript [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 years ago.
Having this string 30/11/2011. I want to convert it to date object.
Do I need to use :
Date d = new Date(2011,11,30); /* months 1..12? */
or
Date d = new Date(2011,10,30); /* months 0..11? */
?
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
The syntax is as follows:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1 = parseInt(str1.substring(0,2));
var mon1 = parseInt(str1.substring(3,5));
var yr1 = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
Very simple:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
First extract the string like this
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
month Integer value representing the month, beginning with 0 for January to 11 for December.
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).

Categories