how to format date YYYYMMDDmmhhssuuu - javascript

I have a 'timestamp' value 20200513134950000 and the format should be YYYYMMDDmmhhssuuu.
I can not wrap my head around how to properly format it. I have tried date-fns library and native Date format, but with no luck.
Any ideas?

You can extract all the relevant parts from the number with a simple regexp or even by counting numbers. Then the only caveat is that months are zero-based, but apart from that, you can just use the standard Date() constructor.
const timestamp = 20200513134950000;
const UTC_mask = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{3})/;
const [
year,
month,
day,
hour,
min,
sec,
ms
] = timestamp.toString().match( UTC_mask ).slice( 1 );
const datetime = new Date( year, parseInt( month, 10 ) - 1, day, hour, min, sec, ms );
console.log( datetime );

Without any library you can just get the parts and pass them to the Date constructor:
let ts = '20200513134950000';
let [c,y,m,d,H,M,S] = ts.match(/\d\d/g);
console.log(new Date(c+y,--m,d,H,M,S).toString());

You can try using DayJS.
Its a lightweight library and allows you to specify custom parse format for parsing the dates.
const dayjs = require('dayjs');
var customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)
console.log(dayjs('20200513134950000', 'YYYYMMDDmmhhssuuu'))

Related

Days between dates in DayJS UK Format

Im using dayjs, and I'm trying to calculate the days between 2 days so that I can output Today, Tomorrow and X days time
The problem I'm having though seems to be with the date formats
const date1 = dayjs('31/10/2021');
const date2 = dayjs().format("DD/MM/YYYY")
let hours = date2.diff(date1, 'days')
No matter how I try, I'm getting date2.diff is not a function when I add .format to date2. Does anyone know how to format this correctly and get the correct outcome?
If i try const date1 = dayjs('31/10/2021').format("DD/MM/YYYY"); then it errors with invalid date
You can try the following:
const date1 = dayjs('2021-01-25');
const date2 = '01/11/2020'; // or '2020-11-01'
let hours = date1.diff(date2, 'day')
console.log(hours) // 380
The format function just returns a string. This is why date2.diff is not a function.
The diff function is only available for dayjs objects (not for strings).
Docs for difference function: https://day.js.org/docs/en/display/difference
Docs for format function: https://day.js.org/docs/en/display/format
const date1 = dayjs('2019-01-25')
date1.diff('2018-06-05', 'day', true)
You don't need to call format function, just use dayjs constructor to convert both dates to dayjs object and return the difference between the 2 dates in number of days.

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

convert string to UTC time using jquery

I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'.
I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string.
function toUTC(str) {
let [h, m] = str.split(':');
let date = new Date();
date.setHours(h, m, 0)
return date.toUTCString();
}
console.log(toUTC('8:3'))
console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date.
let date = new Date('2020-04-01'); // leave the Date parameter blank if today
date.setHours(16); // must be 24 hours format
date.setMinutes(45);
let theUTCFormat = date.getUTCDate();
Cheers,

In moment.js, is it possible to have a date-time string and keep the date but change the time?

I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.
How would I take a string like this and convert it such that the time is different?
This is would I'd expect:
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
moment(dateTimeString)
.changeTime('05:20 PM')
.format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'
There is no built in function like changeTime, you can write your own using set.
You can add changeTime using moment.fn
The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.
You can create a temp moment object with your "time to add" value using moment(String, String), then use set(Object(String, Int)) and getters like hours() and minutes().
Here a live sample:
moment.fn.changeTime = function(timeString) {
let m1 = moment(timeString, 'hh:mm A');
return this.set({h: m1.hours(), m: m1.minutes()});
}
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
moment(dateTimeString)
.changeTime('05:20 PM')
.format()
)
console.log(newDateTimeString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
If the user-entered time is formatted as such 13:00 you could do :
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
var userInput = "13:20"
const newDateTimeString = (
moment(dateTimeString)
.hours(userInput.split(":")[0])
.minutes(userInput.split(":")[1])
.format()
)
Using https://momentjs.com/docs/#/get-set/hour/ and https://momentjs.com/docs/#/get-set/minute/
If it's formatted with PM and AM system, you could to the same, but with a little bit more of parsing, to know if it's 5.00 AM or PM.
One possible way is to use moment to grab the date and then combine it with your custom time value in another moment() call like so:
const newDateTimeString = (
moment(`${moment(dateTimeString).format('YYYY-MM-DD')} 05:20 PM`)
.format()
)

adding one day to my date [duplicate]

I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
Something like this should do the trick:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
To add one day, per the question asked, call it as follows:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
java.time
On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)
Assuming String input and output:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Construct a Calendar object and call add(Calendar.DATE, 1);
Java 8 added a new API for working with dates and times.
With Java 8 you can use the following lines of code:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
Take a look at Joda-Time (https://www.joda.org/joda-time/).
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
Please note that this line adds 24 hours:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
but this line adds one day
cal.add( Calendar.DATE, 1 );
On days with a daylight savings time change (25 or 23 hours) you will get different results!
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.
If you are using Java 8, then do it like this.
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
If you want to use SimpleDateFormat, then do it like this.
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);
This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
It's very simple, trying to explain in a simple word.
get the today's date as below
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);
Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.
System.out.println(calendar.getTime());// print modified date which is tomorrow's date
Thanks
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
With Java SE 8 or higher you should use the new Date/Time API
int days = 7;
LocalDate dateRedeemed = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
String newDate = dateRedeemed.plusDays(days).format(formatter);
System.out.println(newDate);
If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.
public LocalDate asLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
return zdt.toLocalDate();
}
With a version prior to Java SE 8 you may use Joda-Time
Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8
int days = 7;
DateTime dateRedeemed = DateTime.now();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
String newDate = dateRedeemed.plusDays(days).toString(formatter);
System.out.println(newDate);
Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.
Just pass date in String and number of next days
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
Will Print:
1970-12-31
1971-01-01
1970-12-31
Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
It's simple actually.
One day contains 86400000 milliSeconds.
So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then
add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.
Example
String Today = new Date(System.currentTimeMillis()).toString();
String Today will be 2019-05-9
String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();
String Tommorow will be 2019-05-10
String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();
String DayAfterTommorow will be 2019-05-11
You can use this package from "org.apache.commons.lang3.time":
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);
If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.
I'm working with a date in this format: yyyy-mm-dd
You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.
yyyy-MM-dd is the default format of java.time.LocalDate
The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.
Ways to increment a local date by one day
There are three options:
LocalDate#plusDays(long daysToAdd)
LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Parsing
LocalDate ldt = LocalDate.parse("2020-10-20");
System.out.println(ldt);
// Incrementing by one day
LocalDate oneDayLater = ldt.plusDays(1);
System.out.println(oneDayLater);
// Alternatively
oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
System.out.println(oneDayLater);
oneDayLater = ldt.plus(Period.ofDays(1));
System.out.println(oneDayLater);
String desiredString = oneDayLater.toString();
System.out.println(desiredString);
}
}
Output:
2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21
How to switch from the legacy to the modern date-time API?
You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odt);
// Alternatively, using time-zone
odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odt);
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
System.out.println(ldt);
// Alternatively,
ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016
Learn more about the modern Date-Time API from Trail: Date Time.
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Convert to string and back with SimpleDateFormat: This is an inefficient solution.
Convert to LocalDate: You would lose any time-of-day information.
Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
You can do this just in one line.
e.g to add 5 days
Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));
to subtract 5 days
Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));

Categories

Resources